Metoden __debugInfo

Metoden __debugInfo anropas när information om ett objekt skrivs ut av funktionerna var_dump och print_r. Den ska returnera en array med egenskaper som ska visas. Detta gör det möjligt att dölja konfidentiell data eller lägga till ytterligare felsökningsinformation.

Syntax

phppublic function __debugInfo(): array

Exempel

Dölj konfidentiell data vid dumpning av objekt:

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

Resultat av kodkörning:

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

Exempel

Lägg till ytterligare felsökningsinformation:

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

Resultat av kodkörning:

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

Exempel

Filtrera egenskaper för visning:

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

Resultat av kodkörning:

phpConfig Object (
  [cacheEnabled] => 1
)

Se även

  • funktionen var_dump,
    som skriver ut information om en variabel
  • funktionen print_r,
    som skriver ut lättläst information om en variabel