开发者

PHP Indirect modification of overloaded property

i have this simple class:

class A
{
    var $children=array();

    function &__get($name)
    {
        if($name==="firstChild")
        {
            if(count($this->children)) $ret=&$this->children[0];
            else $ret=null;
        }
        return $ret;
    }
}

By accessing the "firstChild" property it should return its first child by reference or null if there are no children.

$a=new A;
$c=&$a->firstChild;

Now if the class contains at least one child it works great but if it doesn't (and it should return null) it triggers the error "Indirect modification of overloaded property".

Why does this happen? I'm not trying to modify anyth开发者_运维百科ing so what is that "Indirect modification"? And why if i remove the reference sign ($c=$a->firstChild;) it works?


I think you should use empty() instead of count(). One reason for that is (quote from manual for count())

If var is not an array or an object with implemented Countable interface, 1 will be returned. There is one exception, if var is NULL, 0 will be returned.

Also, if you're storing objects in this array, you don't have to use references, since (in PHP 5+) objects are passed reference by default.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜