custom var_dump output for my class
In PHP 5.6.0+, you can use the __debugInfo()
magic function to customize the output of var_dump()
.
array __debugInfo ( void )
This method is called by
var_dump()
when dumping an object to get the properties that should be shown. If the method isn't defined on an object, then all public, protected and private properties will be shown.This feature was added in PHP 5.6.0.
Example:
class MyDateTime{ public $year, $month, $day, $hour, $minute, $second; public function __debugInfo() { return array( 'date' => $this->year . "-" . $this->month . "-" . $this->day, 'time' => sprintf("%02d:%02d:%02d", $this->hour, $this->minute, $this->second), ); }}$dt = new MyDateTime();$dt->year = 2014; $dt->month = 9; $dt->day = 20;$dt->hour = 16; $dt->minute = 2; $dt->second = 41;var_dump($dt);
Output by PHP 5.6.0:
object(MyDateTime)#1 (2) { ["date"]=> string(9) "2014-9-20" ["time"]=> string(8) "16:02:41"}
Output by PHP 5.0.0 - 5.5.16:
object(MyDateTime)#1 (6) { ["year"]=> int(2014) ["month"]=> int(9) ["day"]=> int(20) ["hour"]=> int(16) ["minute"]=> int(2) ["second"]=> int(41)}
Notes:
__debugInfo()
must return anarray
. I got an error on PHP 5.6.0 for returning astring
:Fatal error: __debuginfo() must return an array in /somepath/somefile.php on line 15
- It seems to work with
print_r()
too, although this doesn't seem documented anywhere.
For this you could use the ReflectionClass functions and build your own function to get the informations you need.
http://php.net/manual/de/reflectionclass.tostring.php
http://php.net/manual/en/book.reflection.php