Consider the following code-example:
$m_oDate = new DateTime('2013-06-12 15:54:25');
some_func($m_oDate);
echo $m_oDate->{'ROXXOR_IS_BACK!!'};
The most obvious difference to yours is that instead of the print_r
function a different one some_func
is called. The expectations might differ because you know print_r
but you don't know some_func
but that is only to sharpen your senses. Let's wait a moment until I show the definition of that function.
The second difference is the name of the property that is getting echoed. Here I've choosen a name that is really exceptional: {'ROXXOR_IS_BACK!!'}
, again to sharpen your senses.
This name is that crazy that is must be obvious not being part of DateTime
albeit when the example above is executed, it's totally clear that this roxxor property must exists. Program Output:
PHP never lets you down.
So how come? Yes, you sure already have an idea how that works. The some_func()
function must have added it. So let's take a look into the functions definition:
function some_func($m_oDate) {
$m_oDate->{'ROXXOR_IS_BACK!!'} = 'PHP never lets you down.';
}
Yes, it's now clearly visible that this function has added a property to the object. And it also shows that this is totally easily possible with any object in PHP.
Compare with an array in PHP, you can also add new keys when you want to.
This example has not been chosen out of nothing, because this is where objects in PHP come from: They are just syntactic sugar around arrays and this has to with the time when objects in PHP were introduced back in PHP 3:
At the time classes were introduced to the source tree of what was to become PHP 3.0, they were added as syntactic sugar for accessing collections. PHP already had the notion of associative array collections, and the new critters were nothing but a neat new way of accessing them. However, as time has shown, this new syntax proved to have a much more far-reaching effect on PHP than was originally intended.
-- Zeev Suraski about the standard object since PHP 3 (archived copy) - via Why return object instead of array?
This is also the simple explanation why it's totally common in PHP that functions can add member variables which have not been defined earlier in the class. Those are always public.
So when you do assumptions about some object having a property or not, take a look where it comes from. It must not be part of the class but might have been added later.
And keep the following in mind:
Do not use print_r
and var_dump
in production code.
print_r
is commented out in the second – Ceratoidecho
, not theprint_r
– Crashawprint_r()
; granted, it probably resulted from a mistake in the first place :) – Capitolineprint_r()
instead of justObject
. I feel that was a mistake :) – Capitoline<sarcasm>
tag was intentionally omitted ;-) – Capitolinesome_func()
function is called on DateTime. I guess, the reason why that is possible are the same as with theprint_r
function. – Teach