empty() returning TRUE on object's non-empty property

前提是你 提交于 2020-01-03 14:56:16

问题


I've got a very weird and unexpected problem.

empty() is returning TRUE on a non-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)

Would this mean, that the __get() magic function is not called when using empty()?

btw. I'm running PHP version 5.0.4


回答1:


Yes, that's what it means. empty is not your everyday function, it's a language construct that doesn't play by normal rules. Because in fact, $obj->property does not exist, so the result is correct.

You'll need to implement __isset() for empty and isset to work.




回答2:


If you want to use empty or isset with properties, you need to declare a member function called __isset.

Here's a possible implementation:

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

    return isset($this->$priv_name);
}



回答3:


if (isset(($this->$priv_name)))

Putting () around the Object->Property value will force it to be evaluated prior to calling isset.



来源:https://stackoverflow.com/questions/3060420/empty-returning-true-on-objects-non-empty-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!