一、语法
__debugInfo ( ) : array
在PHP 5.6.0中,当转储一个对象以获得应该显示的属性时,var_dump()调用此方法。如果该方法没有在对象上定义,那么将显示所有公共的、受保护的和私有的属性。
二、示例
<?php
/**
* 定义一个狗类
*/
class Cat {
//定义一个属性
private $name = null;
// 构造函数
function __construct(?string $name = null){
if(is_null($this->name)){
$this->setName($name);
}
}
/**
* 输出名字
*/
public function getName(){
echo "这是一只猫,名字叫{$this->name}。\n"."<br>";
}
/**
* 私有方法
*/
private function setName($name){
$this->name = $name;
}
public function __toString() {
return '这是一只猫,名字叫'.$this->name.'。<br>';
}
public function __debugInfo() {
return [
'name_xxx' => $this->name,
];
}
}
//实例化
$Cat = new Cat('旺财'); // 输出 __construct
echo $Cat; //输出:'这是一只猫,名字叫旺财。
var_dump($Cat); //输出:object(Cat)#1 (1) { ["name_xxx"]=> string(6) "旺财" }
三、其他
如果想了解更多,请前往:https://www.php.net/manual/zh/language.oop5.magic.php#object.debuginfo
浙公网安备 33010602011771号