Php Magic方法和空

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.

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';
}

It does not make sense when used with anything other than the variable; ie empty (addslashes ($ name)) does not make sense, since it will be checked by anything other than a variable as a variable with a value of FALSE.

In your case, you should use the type conversion:

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

change

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

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

And then try

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';
}