我的类的自定义var_dump输出

ami*_*mik 11 php var-dump

是否可以覆盖自定义类的var_dump输出?我想要这样的东西:

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
  }
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用一些第三方var_dump替代品,但我想在我的库项目中自定义var_dump的行为.

谢谢.

Pan*_*ang 14

PHP 5.6.0+中,您可以使用__debugInfo()magic函数来自定义输出var_dump().

array __debugInfo ( void )

var_dump()转储对象以获取应显示的属性时,将调用此方法.如果未在对象上定义该方法,则将显示所有公共属性,受保护属性和私有属性.

PHP 5.6.0中添加了此功能.

例:

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);
Run Code Online (Sandbox Code Playgroud)

PHP 5.6.0输出:

object(MyDateTime)#1 (2) {
  ["date"]=>
  string(9) "2014-9-20"
  ["time"]=>
  string(8) "16:02:41"
}
Run Code Online (Sandbox Code Playgroud)

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)
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  1. __debugInfo()必须归还array.我在PHP 5.6.0上遇到错误,返回一个string:

    致命错误:__ debuginfo()必须在第15行的/somepath/somefile.php中返回一个数组

  2. 它似乎print_r()也适用,虽然这似乎没有在任何地方记录.


Ren*_*hle 1

为此,您可以使用 ReflectionClass 函数并构建您自己的函数来获取您需要的信息。

http://php.net/manual/de/reflectionclass.tostring.php
http://php.net/manual/en/book.reflection.php