Empty () returns TRUE for the object non-empty property

I have a very strange and unexpected problem.

empty()returns a TRUEnon-empty property for a reason unknown to me.

class MyObject
{
    private $_property;

    public function __construct($property)
    {
        $this->_property = $property;
    }

    public function __get($name)
    {
        $priv_name = "_{$name}";

        if (isset($this->$priv_name))
        {
            return $this->$priv_name;
        }
        else
        {
            return NULL;
        }
    }
}

$obj = new MyObject('string value');

echo $obj->property;        // Output 'string value'
echo empty($obj->property); // Output 1 (means, that property is empty)

Will this mean that the magic function is __get()not called when used empty()?

by the way. I am running PHP version 5.0.4

+3
source share
3 answers

Yes, that is what it means. empty- this is not your everyday function, it is a language construct that is not reproduced by ordinary rules. Because it really $obj->propertydoes not exist, so the result is correct.

You need to implement__isset() for emptyand issetfor work.

+8

empty isset , -, __isset.

:

public function __isset($name)
{
    $priv_name = "_{$name}";

    return isset($this->$priv_name);
}
+4
if (isset(($this->$priv_name)))

Putting () around the value of Object-> Property will cause it to evaluate before the call isset.

-1
source

Source: https://habr.com/ru/post/1750456/


All Articles