__debugInfo metodi

__debugInfo metodi obyekt haqida ma'lumot chiqarayotganda var_dump va print_r funksiyalari tomonidan chaqiriladi. U ko'rsatilishi kerak bo'lgan xususiyatlarni o'z ichiga olgan massivni qaytarishi kerak. Bu maxfiy ma'lumotlarni yashirish yoki qo'shimcha debug ma'lumotlarini qo'shish imkonini beradi.

Sintaksis

phppublic function __debugInfo(): array

Misol

Obyektni dump qilganda maxfiy ma'lumotlarni yashirish:

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

Kodni bajarish natijasi:

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

Misol

Qo'shimcha debug ma'lumotlarini qo'shish:

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

Kodni bajarish natijasi:

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

Misol

Ko'rsatish uchun xususiyatlarni filtrlash:

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

Kodni bajarish natijasi:

phpConfig Object (
  [cacheEnabled] => 1
)

Shuningdek qarang

  • var_dump funksiyasi,
    o'zgaruvchi haqida ma'lumot chiqaradi
  • print_r funksiyasi,
    o'zgaruvchi haqida o'qish uchun qulay ma'lumot chiqaradi