PHP: Unexpected behavior when using unset() on class properties

When you unset a non-dynamic class property you apparently enter a weird limbo state.

Take the following simple anonymous class:

//Simple anonymous class, nothing to special
$c =    new class
        {
            public $alpha = 'alpha';
        };

Perform a property exists test and show the value:

//Do we have the property?
echo property_exists( $c, 'alpha' ) ? 'true' : 'false', "\n";   //true

//Display it
echo $c->alpha, "\n"; //alpha

Now unset it:

//Unset it
unset( $c->alpha );

Perform the exact same property test again:

//Do we have the property still?
echo property_exists( $c, 'alpha' ) ? 'true' : 'false', "\n";   //true!!

Umm… true? Ok, I’m cool with that, its part of the class’s definition so maybe it must always exist. I guess. Anyway, since we know that property exists let’s use it:

//Display it
echo $c->alpha, "\n"; //Undefined property: class@anonymous::$alpha

Wait, what? Undefined property. But you said that the property existed!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.