views:

28

answers:

1

Hi, 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 anything so what is that "Indirect modification"? And why if i remove the reference sign ($c=$a->firstChild;) it works?

+1  A: 

I think you should use empty() instead of count(). One reason for taht is (qquote 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 eferences, since (in PHP 5+) objects are passed beference by default.

Mchl