custom var_dump output for my class

amik picture amik · May 17, 2013 · Viewed 9.5k times · Source

is it possible to override var_dump output for a custom class? I want something like this:

class MyClass{
    public $foo;
    public $bar;
    //pseudo-code
    public function __dump($foo, $bar)
    {
        return 'Foo:$foo, bar:$bar';
    }
}

var_dump(array($instanceOfMyClass));
//it should output this:
array(1) {
  [0] =>
  class MyClass#1 (2) {
    Foo:valueOfFoo, bar:valueOfBar
  }
}

I know I can use some 3rd-party var_dump alternatives, but I want to customize behavior for var_dump in my library project.

Thanks.

Answer

Pang picture Pang · Sep 20, 2014

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:

  1. __debugInfo() must return an array. I got an error on PHP 5.6.0 for returning a string:

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.