Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php Magic Methods and Empty

Tags:

php

Having the following code

class test {
    private $name;
    public function __get($name){
        return $name;
    }
    public function __set($name,$value){
        $this->name = $value;
    }
}
$obj = new test();
$obj->a = 2;

if (!empty($obj->a)) {
    echo 'not empty';
}

This is calling __isset. But this is not being defined so it always return empty. What is the best way to check for a non empty property?

Update :changing the class is not a solution because it's a 3th party component and it has to remain intact.

like image 267
johnlemon Avatar asked Apr 24 '26 16:04

johnlemon


2 Answers

If you can't change the class, I think the only possible workaround is using a temporary variable.

$obj->a = 2;

$test = $obj->a; 

if (!empty($test)) {
    echo 'not empty';
}
like image 184
Pekka Avatar answered Apr 27 '26 10:04

Pekka


I know I am very late to the party here, however I am posting this for the edificationof any who may stumble across this question.

Firstly, I believe that the test class is wrong and if that is really what the 3rd party component does, I would chuck it out because it's rubbish. Do you really want all property names to map internally to the single property 'name', and thereby overwrite each other? Do you really want all property names to be returned as the property value? The code should look like this:

class test {
    public function __get($name){
        return $this->$name;
    }
    public function __set($name,$value){
        $this->$name = $value;
    }
}

Secondly, you can change the class, even if it has to remain intact. That's the point of inheritance. This is the open-closed principle. If the functions are incorrect, simply extend test like this to correct them:

class test {
    private $name;
    public function __get($name){
        return $name;
    }
    public function __set($name,$value){
        $this->name = $value;
    }
}

class my_test extends test
{
    public function __get($name)
    {
        return $this->$name;
    }

    public function __set($name,$value){
        $this->$name = $value;
    }
}

You shouldn't need to define __isset() as the corrected code will do what it is meant to do, but if you did you could do that here too.

Now the following will do what it is supposed to do (note the change of class name):

$obj = new my_test();
$obj->a = 2;

if (!empty($obj->a)) {
    echo 'not empty';
}
like image 36
Duncan Avatar answered Apr 27 '26 12:04

Duncan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!