Verification: a143cc29221c9be0

Objects and arrays in php

Private and Protected properties

If we start adding private and protected properties to our Foo class, things get very interesting:

The output will be like following in this case:

array(3) {
    ["bar"]=> string(8) "barValue"
    ["*baz"]=> string(8) "bazValue"
    ["Footab"]=> string(8) "tabValue"

Weird, so $baz is copied to array key '*baz' and $tab is copied to Footab...

Let's try accessing those keys:

Something even more strange happens here: we get two notices.

Notice: Undefined index: *baz in [...] on line [...]

Notice: Undefined index: Footab in [...] on line [...]

I actually spent some time trying to understand why this was happening, and even the debugger was failing me! Then I tried using var_export:

The output is quite interesting:

array (
    'bar' => 'barValue',
    '' . "\0" . '*' . "\0" . 'baz' => 'bazValue',
    '' . "\0" . 'Foo' . "\0" . 'tab' => 'tabValue',

Null characters are used as delimiters between the visibility scope of a particular property and its name!

That's some really strange results, and they give us some insight on how PHP actually keeps us from accessing private and protected properties.

Direct property read attempt

What happens if we try to directly access the $foo properties with this new trick?


Looks like the engine was patched after PHP 5.1 to fix this (un-documented break), since we get a fatal:

Fatal error: Cannot access property started with '\0' in [...] on line [...]

Too bad! That would have had interesting use cases. The change makes sense though, since we shouldn't modify internal state without explicitly using an API that cries out "I do things with your objects state!".