0

If I create and instance of the DateTime class, then vardump() it:

<?php
$date = new DateTime;    
var_dump($date);

output:

object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2016-12-22 00:21:21.022426"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}

In this case var_dump is not explicitly reporting that the values of date or timezone are public, but my experience with var_dump is that unless it reports otherwise (i.e. with a label like [private:date]), all properties are assumed to be public.
This implies to me that you should then be able to run code like

<?php
$date = new DateTime;
echo $date->timezone;

and the output should contain the string UTC but instead it contains nothing (or more specifically the NULL value).

I understand that this is not the correct way to use DateTime for retrieving timezone, but having PHP report an object as having public properties that you cannot then access seems to violate a fundamental rule of objects, namely that they hold properties that - if public - you can access them.

Why does var_dump report these properties, yet when I try to access them, they evaluate to NULL?

the_velour_fog
  • 2,094
  • 4
  • 17
  • 29
  • Take a look at [`__debugInfo()`](http://php.net/manual/en/language.oop5.magic.php#object.debuginfo), it's how `var_dump()` shows properties that do not exist. However `DateTime` is an internal class and might work differently, but this should answer how `var_dump()` can generate 'properties' that do not exist. – Xorifelse Dec 22 '16 at 00:57
  • tried `echo $date->getTimezone()->getName()` ? – Bagus Tesa Dec 22 '16 at 00:59
  • @Xorifelse ah thanks, I think I understand. so say for example you wrote a class `MyClass` and you wanted a `var_dump($myclassinstance)` to show "extra" properties that might not otherwise be revealed in a `var_dump` you could use `__debugInfo()` to essentially register those "extra" properties for `var_dump()` to get at? – the_velour_fog Dec 22 '16 at 01:19
  • @the_velour_fog The returned value from `__debugInfo()` *is* the output of `var_dump()`, so nothing "extra". I wanted to post an answer explaining this, but it was closed. – Xorifelse Dec 22 '16 at 01:34
  • @Xorifelse ah ok, I guess you could post the answer on the original question. I just wrote a class using `__debugInfo()` and it behaved as per my comment above. What I didn't expect is that `__debugInfo()` seems to blow away all the normal output of `var_dump()` though. – the_velour_fog Dec 22 '16 at 01:39

0 Answers0