A __debugInfo metódus
A __debugInfo metódus akkor hívódik meg, amikor az objektum információit a
var_dump és print_r függvényekkel jelenítjük meg. Egy tömböt kell visszaadnia azon tulajdonságokkal,
amelyeket meg kell jeleníteni. Ez lehetővé teszi a bizalmas adatok elrejtését
vagy további hibakeresési információk hozzáadását.
Szintaxis
public function __debugInfo(): array
Példa
Bizalmas adatok elrejtése az objektum kiírásakor:
<?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);
?>
A kód végrehajtásának eredménye:
object(User)#1 (2) {
["name"]=> string(4) "John"
["password"]=> string(6) "******"
}
Példa
További hibakeresési információk hozzáadása:
<?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);
?>
A kód végrehajtásának eredménye:
object(Product)#1 (3) {
["id"]=> int(101)
["price"]=> int(100)
["price_with_tax"]=> float(120)
}
Példa
Tulajdonságok szűrése a megjelenítéshez:
<?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);
?>
A kód végrehajtásának eredménye:
Config Object (
[cacheEnabled] => 1
)