Hide specific class fields from print_r or var_dump

前端 未结 6 1584
无人及你
无人及你 2021-01-02 01:22

Is it possible to hide a specific class fields from print_r ?



        
6条回答
  •  生来不讨喜
    2021-01-02 01:47

    New Magic method __debugInfo() was introduced in PHP 5.6 that will allow you to modify the default behaviour of var_dump() when dumping your objects.

    Have a look at the documentation.

    Example:

    prop = $val;
        }
    
        public function __debugInfo() {
            return [
                'propSquared' => $this->prop ** 2,
            ];
        }
    }
    
    var_dump(new C(42));
    ?>
    

    Returns:

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

    Although this question is 4 years old, I'm sure someone will find this useful in the future.

提交回复
热议问题