361 of 410 menu

The __debugInfo Method

The __debugInfo method is called when outputting object information by functions var_dump and print_r. It must return an array with properties to be displayed. This allows hiding confidential data or adding additional debug information.

Syntax

public function __debugInfo(): array

Example

Hiding confidential data when dumping an object:

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

Code execution result:

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

Example

Adding additional debug information:

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

Code execution result:

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

Example

Filtering properties for display:

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

Code execution result:

Config Object ( [cacheEnabled] => 1 )

See Also

  • the var_dump function,
    which outputs information about a variable
  • the print_r function,
    which outputs human-readable information about a variable
byenru