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
public function __debugInfo(): array
Ví dụ
Ẩn dữ liệu bí mật khi dump đối tượng:
<?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ã:
object(User)#1 (2) {
["name"]=> string(4) "John"
["password"]=> string(6) "******"
}
Ví dụ
Thêm thông tin gỡ lỗi bổ sung:
<?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ã:
object(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
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ã:
Config Object (
[cacheEnabled] => 1
)