php调试,自定义类__debugInfo与__toString方法有何区别?
发布于 作者:苏南大叔 来源:程序如此灵动~
对php自定义类的格式化输出,做有益的探讨。本文要探讨的主要内容是:每个php类都自带的方法__debugInfo()和__toString()。主要应用场景是:各种php代码调试信息输出场景。

苏南大叔的“程序如此灵动博客”,记录苏南大叔的代码感想和感悟。本文测试环境:win10,nginx@1.15.11,php@8.2.10-nts。
__debugInfo()
这个__debugInfo()是内置的方法,名称不可以改变。否则就无法被自动触发了。定义如下:
class Cat
{
private $name = null;
public function __construct(string $name = null) {
$this->name = $name;
}
public function __debugInfo() {
// return '宠物猫[' . $this->name . ']:喵喵喵'; // error
return [
'name' => $this->name,
'time' => time()
];
}
}__debugInfo()的返回值必须是个array,返回字符串是不行的。会得到如下类似报错信息:
Fatal error: __debuginfo() must return an array触发:
$pet = new Cat('旺财');
var_dump($pet->__debugInfo());
var_dump($pet); // object(Cat)#1 (2) {}
print_r($pet); // Cat Object{}输出:
object(Cat)#1 (2) {
["name"]=>
string(6) "旺财"
["time"]=>
int(1696742026)
}
object(Cat)#1 (2) {
["name"]=>
string(6) "旺财"
["time"]=>
int(1696742026)
}
Cat Object
(
[name] => 旺财
[time] => 1696742026
)__toString()
这个__toString()也是内置的方法,名称不可改变,否则无法被动触发。定义如下:
class Cat
{
private $name = null;
public function __construct(string $name = null) {
$this->name = $name;
}
public function __toString() {
return '宠物猫[' . $this->name . ']:喵喵喵';
// return [ 'name' => $this->name ]; // error
}
}返回值必须是个string,否则报错类似:
<b>Fatal error</b>: Uncaught TypeError: Cat::__toString(): Return value must be of type string, array returned in触发:
$pet = new Cat('旺财');
echo $pet->__toString();
echo $pet; // 宠物猫[旺财]:喵喵喵
// die($pet);
// exit($pet);输出:
宠物猫[旺财]:喵喵喵
宠物猫[旺财]:喵喵喵__debugInfo() vs __toString()
__debugInfo()和__toString()两个方法做对比的话,区别就主要是使用场景的不同。
__debugInfo()侧重于debug,所以可以输出很多细节信息,返回值必须是array,使用var_dump()可以触发。__toString()的debug的属性则不是那么明显,输出的话则规定了是字符串,可以使用echo或者print_r()触发。

| 方法 | 返回值类型 | 触发方式 |
|---|---|---|
| __debugInfo() | array | var_dump() / print_r() |
| __toString() | string | echo / die() / exit() |
相关文章
- https://newsn.net/say/thinkphp-exception.html
- https://newsn.net/say/thinkphp5-debug.html
- https://newsn.net/say/php-trace-plus.html
- https://newsn.net/say/php-debug-func.html
结束语
其实var_dump()和echo都是经常使用的调试手段,但是从细节上探讨的话,居然是调用的不同的对象方法。如果对苏南大叔的php相关经验文章感兴趣,可以参考: