我的类的自定义var_dump输出

时间:2013-05-17 13:30:27

标签: 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
  }
}

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

感谢。

4 个答案:

答案 0 :(得分:13)

PHP 5.6.0 + 中,您可以使用__debugInfo()魔术功能自定义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);

PHP 5.6.0的输出:

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

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)
}

注意:

  1. __debugInfo()必须返回array。我在PHP 5.6.0上收到错误,因为它返回string

      

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

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

您无法覆盖核心PHP函数。

您可以在对象中添加函数__toString():

class myClass {
    public function __toString(){
        // custom var_dump() content here then output it
    }
}

$myClass = new myClass();

echo $myClass;

答案 3 :(得分:0)

不要有意义覆盖var_dump结果,你可以使用toString()魔术方法

class MyClass{
public $foo;
public $bar;
public function test(){}
public function __toString()
 {
    $vars="Variables:";
    foreach(get_class_vars(__CLASS__) as $name => $value) $vars.="<br> $name : {$this->{$name}}".gettype($this->{$name});
    return __CLASS__.':<br>'.$vars.'<br>Methods:<br>'.implode('<br>',get_class_methods(__CLASS__));
 }
}

$lol = new MyClass();
$lol->foo = 10;
$lol->bar = 'asd';

 echo $lol;

示例HERE