I don't consider this a duplicate, per say, since the other question speaks of var_dump not print_r. I think others might run into the issue using print_r and thus they would find my question and the answers and might miss the other questions. I did, not find the other one, that is.
I was writing some code to calculate a date by subtracting a number of days from the current date. I got the current date with the getdate()
function. I then used date_sub()
to subtract the days.
While testing I had some problems and so I put in some echo
and print_r()
statements.
I finally got it working as I wanted and I took out the echo
and print_r()
statements.
When I ran the code I got an error: E_NOTICE : type 8 -- Undefined property: DateTime::$date -- at line 8
The statement in question was a reference to the DateTime object's date element. I thought that perhaps I had screwed up when I commented out the echo
and print_r()
statements so I undid the changes and tried it - it worked with no error.
I then very carefully removed the echo
and print_r()
stagements and tried it again - bang! same error.
I sat and stared at the screen for awhile and began to figure out which echo
and print_r()
statement was preventing the error. I finally narrowed it down to one print_r() that displayed the DateTime object. If I left it in, no error occurred and the output was correct. If I commented it out - the error occurred.
I did some more staring and then went to find out what another way to reference the DateTime object's data element. I found i could get the same results with object->format()
But the bizarre behavior has a grip on me and I came here to present it and see if anyone has any theories as to why it is happening.
Here's the bare minimum coded needed to demonstrate the issue
<?php
$today = date_create();
print_r($today);
echo '<br>';
print_r($today->date);
?>
It is the second statement - print_r($today);
- which somehow allows me to access the date element as $today->date without an error.
The output will be something like:
DateTime Object ( [date] => 2015-12-22 21:00:34.000000 [timezone_type] => 3 [timezone] => America/New_York )
2015-12-22 21:00:34.000000
If you comment out that statement, you'll get:
E_NOTICE : type 8 -- Undefined property: DateTime::$date -- at line 5
You probably are having trouble believing this - go to fiddle.org and play with the code.
Comment out the first print_r() and you get the error. Un-comment and you don't get an error.
If you replace the print_r()
statement with with one that does not reference the DateTime object, such as print_r('Hey there');
-- you will get the error. It is not the print_r() function itself, it is the print_r()
call with the DateTime that somehow prevents the error.
So - any thoughts on what that print_r()
statement is doing that enables the "incorrect" reference to the DateTime object's data element.