php – 为我的类定制var_dump输出

前端之家收集整理的这篇文章主要介绍了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的行为.

谢谢.

PHP 5.6.0中,您可以使用 __debugInfo()魔术功能自定义 var_dump()输出.

array __debugInfo ( void )

This method is called by 07001 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.

例:

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

笔记:

> __debugInfo()必须返回一个数组. PHP 5.6.0中有一个错误返回一个字符串:

Fatal error: __debuginfo() must return an array in /somepath/somefile.PHP on line 15

>它似乎与print_r()一起工作,虽然这似乎没有记录在任何地方.

原文链接:https://www.f2er.com/php/131033.html

猜你在找的PHP相关文章