PHP对重载属性的间接修改

PHP对重载属性的间接修改,php,class,properties,overloading,Php,Class,Properties,Overloading,我有一个简单的课程: class A { var $children=array(); function &__get($name) { if($name==="firstChild") { if(count($this->children)) $ret=&$this->children[0]; else $ret=null; }

我有一个简单的课程:

class A
{
    var $children=array();

    function &__get($name)
    {
        if($name==="firstChild")
        {
            if(count($this->children)) $ret=&$this->children[0];
            else $ret=null;
        }
        return $ret;
    }
}
通过访问“firstChild”属性,它应该通过引用返回其第一个子级,如果没有子级,则返回null

$a=new A;
$c=&$a->firstChild;
现在,如果类至少包含一个子类,那么它工作得很好,但是如果它不包含(并且应该返回null),那么它将触发错误“间接修改重载属性”


为什么会发生这种情况?我不想修改任何东西,那么什么是“间接修改”?为什么我要删除参考号(
$c=$a->firstChild;
),它会起作用呢?

我认为你应该使用
empty()
而不是
count()
。原因之一是(引用手册中的
count()

如果var不是数组或具有实现的可数接口的对象,则返回1。有一个异常,如果var为NULL,则返回0

另外,如果您在这个数组中存储对象,则不必使用引用,因为(在PHP5+中)对象在默认情况下是通过引用传递的