Die __debugInfo Metode

Die metode __debugInfo word geroep wanneer inligting oor 'n objek deur die funksies var_dump en print_r uitgevoer word. Dit moet 'n skikking terugstuur met die eienskappe wat vertoon moet word. Dit laat jou toe om vertroulike data weg te steek of bykomende debug-inligting by te voeg.

Sintaksis

phppublic function __debugInfo(): array

Voorbeeld

Versteek vertroulike data wanneer 'n objek gedump word:

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

Resultaat van die kode-uitvoering:

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

Voorbeeld

Voeg bykomende debug-inligting by:

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

Resultaat van die kode-uitvoering:

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

Voorbeeld

Filter eienskappe vir vertoning:

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

Resultaat van die kode-uitvoering:

phpConfig Object (
  [cacheEnabled] => 1
)

Sien ook

  • die funksie var_dump,
    wat inligting oor 'n veranderlike uitskryf
  • die funksie print_r,
    wat 'n leesbare weergawe van inligting oor 'n veranderlike uitskryf