__debugInfo 메서드

__debugInfo 메서드는 객체 정보를 var_dump 및 print_r 함수로 출력할 때 호출됩니다. 이 메서드는 표시할 속성들을 배열로 반환해야 합니다. 이를 통해 민감한 데이터를 숨기거나 추가적인 디버그 정보를 넣을 수 있습니다.

구문

phppublic function __debugInfo(): array

예시

객체 덤프 시 민감한 데이터 숨기기:

php<?php
  class User {
    private $password;
    public $name;
    
    public function __construct($name, $password) {
      $this->name = $name;
      $this->password = $password;
    }
    
    public function __debugInfo() {
      return [
        'name' => $this->name,
        'password' => '******'
      ];
    }
  }
  
  $user = new User('John', 'secret123');
  var_dump($user);
?>

코드 실행 결과:

phpobject(User)#1 (2) {
  ["name"]=> string(4) "John"
  ["password"]=> string(6) "******"
}

예시

추가 디버그 정보 넣기:

php<?php
  class Product {
    public $id;
    public $price;
    
    public function __construct($id, $price) {
      $this->id = $id;
      $this->price = $price;
    }
    
    public function __debugInfo() {
      return [
        'id' => $this->id,
        'price' => $this->price,
        'price_with_tax' => $this->price * 1.2
      ];
    }
  }
  
  $product = new Product(101, 100);
  var_dump($product);
?>

코드 실행 결과:

phpobject(Product)#1 (3) {
  ["id"]=> int(101)
  ["price"]=> int(100)
  ["price_with_tax"]=> float(120)
}

예시

표시할 속성 필터링하기:

php<?php
  class Config {
    private $dbHost = 'localhost';
    private $dbUser = 'admin';
    private $cacheEnabled = true;
    
    public function __debugInfo() {
      return [
        'cacheEnabled' => $this->cacheEnabled
      ];
    }
  }
  
  $config = new Config();
  print_r($config);
?>

코드 실행 결과:

phpConfig Object (
  [cacheEnabled] => 1
)

함께 보기

  • var_dump 함수,
    변수에 대한 정보를 출력하는 함수
  • print_r 함수,
    변수에 대한 가독성 좋은 정보를 출력하는 함수