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.
The var_dump() function is used to dump information about a variable. This function displays structured information such as type and value of the given variable. Arrays and objects are explored recursively with values indented to show structure. This function is also effective with expressions.
The var_dump() function dumps information about one or more variables. The information holds type and value of the variable(s).
We have already learned that var_dump() function is used to display structured information (type and value) about one or more expressions. The function outputs its result directly to the browser.
var_dump() displays values along with data types as output. print_r() displays only value as output. It does not have any return type. It will return a value that is in string format.
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.
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()
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
print_r()
too, although this doesn't seem documented anywhere.For this you could use the ReflectionClass functions and build your own function to get the informations you need.
http://php.net/manual/de/reflectionclass.tostring.php
http://php.net/manual/en/book.reflection.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With