Phương thức __debugInfo

Phương thức __debugInfo được gọi khi xuất thông tin về đối tượng bởi các hàm var_dump và print_r. Nó phải trả về một mảng chứa các thuộc tính cần được hiển thị. Điều này cho phép ẩn dữ liệu bí mật hoặc thêm thông tin gỡ lỗi bổ sung.

Cú pháp

phppublic function __debugInfo(): array

Ví dụ

Ẩn dữ liệu bí mật khi dump đối tượng:

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);
?>

Kết quả thực thi mã:

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

Ví dụ

Thêm thông tin gỡ lỗi bổ sung:

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);
?>

Kết quả thực thi mã:

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

Ví dụ

Lọc thuộc tính để hiển thị:

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);
?>

Kết quả thực thi mã:

phpConfig Object (
  [cacheEnabled] => 1
)

Xem thêm

  • hàm var_dump,
    hiển thị thông tin về biến
  • hàm print_r,
    hiển thị thông tin dễ đọc về biến