phpclassvar-dump

does var_dump() shows class properties?


If I use var_dump to some class, say DateTime:

<?php

$date = new DateTime();

var_dump($date);

I got

/var/www/php/test/index.php:5:
object(DateTime)[1]
  public 'date' => string '2021-02-16 23:23:10.768097' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/Berlin' (length=13)

Which I interpret there are 3 public properties. So I try to access them:

<?php

$date = new DateTime();

var_dump($date);

//example of accessing public $date; of class DateTime;
echo $date->date;

but I got Undefined property: DateTime::$date in /var/www/php/test/index.php on line 7

So how should I interpret var_dump(some class)?


Solution

  • var_dump() shows both public and private properties.

    For PHP up to 7.3 date was a public property of DateTime.

    From PHP 7.4 date is a private property, and attempting to access it returns an Undefined property message.

    See https://3v4l.org/MW498

    Note that these properties are not documented in the PHP manual for DateTime, so anything you do with them might break, without notice.