Using the DateTime
class, if I try to run the following code:
$mydate = new DateTime();
echo $mydate->date;
I'll get back this error message
Notice: Undefined property: DateTime::$date...
Which doesn't make sense because when running var_dump()
on the variable $mydate
, it clearly shows that this property exists and is publicly accessible:
var_dump($mydate);
object(DateTime)[1]
public 'date' => string '2012-12-29 17:19:25' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'UTC' (length=3)
Is this a bug within PHP or am I doing something wrong? I'm using PHP 5.4.3.
Beside from using
DateTime::format()
you can access the property using reflection:This is slight faster than using
format()
becauseformat()
formats a timestring that has already been formatted. Especially if you do it many times in a loop.However this is not a regular behaviour of PHP. A bugreport has already been filed as @Nile mentioned in the comments above.
As noted by the other answers, it is an issue with PHP which is unresolved as of today but if it is a 'side effect' of
var_dump()
I am not so sure..What I am sure about is that if the properties of
DateTime
where meant to be used by us it would have been made available. But like many internal classes they are not and you shouldn't rely on "hacky" or "glitchy" methods to fix your code. Instead you should use their API.If you are not satisfied you can extend the class or perhaps use Carbon that extends it for you.
If you wounder how
var_dump()
creates a fake output of an object take a look at__debugInfo()
If you just use a var_Dump before ask the property date everything works allright:
This delivers:
So you see the property date exists even for the object. I can't understand this behaviour. Just comment out the var_Dump and you will get the error again.
This is a known issue.
For some reason, you're not supposed to be able to access the property but
var_dump
shows it anyways. If you really want to get the date in that format, use theDateTime::format()
function.