PHP魔术方法__debugInfo()

2018-09-18 23:00 By "Powerless" 4224 0 1

如果__debugInfo()没有定义,则var_dump()方法会输出对象中的所有属性。

示例代码如下:

<?php
class C {
    private $prop;
    public function __construct($val) {
        $this->prop = $val;
    }
    /**
     * @return array
     */
    public function __debugInfo() {
        return [
            'propSquared' => $this->prop ** 2,
        ];
    }
}
var_dump(new C(42));

输出结果如下:

object(C)#1 (1) { ["propSquared"]=> int(1764) }

注意:__debugInfo()方法只能用于PHP 5.6.0及更高版本。

评 论

View in WeChat

Others Discussion

  • Redis各种数据类型的使用场景举例分析【三】
    Posted on 2018-11-22 17:00
  • 投票通过,PHP 8 确认引入 Union Types 2.0
    Posted on 2019-11-18 22:22
  • PHP设计模式 - 委托模式
    Posted on 2019-04-25 16:15
  • BASE原则
    Posted on 2020-12-17 16:42
  • PHP扩展安装
    Posted on 2019-06-24 11:28
  • 程序员年中考试题-段子版
    Posted on 2021-06-23 15:57
  • 一些常见的基础概念
    Posted on 2018-11-28 19:10
  • HTTP和HTTPS的区别
    Posted on 2020-08-10 23:00