是否可以覆盖自定义类的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的行为。
感谢。
答案 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);
object(MyDateTime)#1 (2) {
["date"]=>
string(9) "2014-9-20"
["time"]=>
string(8) "16:02:41"
}
object(MyDateTime)#1 (6) {
["year"]=>
int(2014)
["month"]=>
int(9)
["day"]=>
int(20)
["hour"]=>
int(16)
["minute"]=>
int(2)
["second"]=>
int(41)
}
__debugInfo()
必须返回array
。我在PHP 5.6.0上收到错误,因为它返回string
:
致命错误:__ debuginfo()必须在第15行的/somepath/somefile.php中返回一个数组
print_r()
,虽然这似乎没有记录在任何地方。
答案 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