Kaedah __debugInfo

Kaedah __debugInfo dipanggil apabila maklumat tentang objek dikeluarkan oleh fungsi var_dump dan print_r. Ia harus mengembalikan array dengan sifat-sifat yang perlu dipaparkan. Ini membolehkan menyembunyikan data sulit atau menambah maklumat debug tambahan.

Sintaks

phppublic function __debugInfo(): array

Contoh

Sembunyikan data sulit ketika dump objek:

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

Keputusan pelaksanaan kod:

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

Contoh

Tambah maklumat debug tambahan:

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

Keputusan pelaksanaan kod:

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

Contoh

Tapis sifat untuk paparan:

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

Keputusan pelaksanaan kod:

phpConfig Object (
  [cacheEnabled] => 1
)

Lihat juga

  • fungsi var_dump,
    yang mengeluarkan maklumat tentang pembolehubah
  • fungsi print_r,
    yang mengeluarkan maklumat boleh-baca mudah tentang pembolehubah