Wednesday, February 24, 2010

PHP: __get && isset


Encountered strange behaviour with php today. If __get is implemented in a class (to provide some properties that are calculated on the fly for example), isset returns false for mentioned calculated properties.



Check out this simple example


class exampleA
{
    __get($property)
    {
        return ($property == 'calculatedProperty')
            ? 42 //do some resource heavy calculation, like meaning of life
            : false;
    }
}
isset($exampleA->calculatedProperty) === false


This is not a bug but a feature according to PHP staff. Btw there is rationality behind it, as there is a __isset in place.

This should work


class exampleB extends exampleA
{
    __isset($property)
    {
        return ($property == 'calculatedProperty') ? true : false;
    }
}
isset($exampleB->calculatedProperty) === true


Maybe this is obvious to everybody, it surprised me at first run, but its correct behavior.

No comments: