Phương thức __serialize
Phương thức ma thuật __serialize được gọi khi tuần tự hóa một đối tượng
bởi hàm serialize. Nó phải trả về một mảng dữ liệu sẽ được
tuần tự hóa. Phương thức này xuất hiện trong PHP 7.4 như một giải pháp thay thế cho
phương thức __sleep với khả năng kiểm soát linh hoạt hơn quá trình tuần tự hóa.
Cú pháp
public function __serialize(): array
Ví dụ
Hãy tạo một lớp với phương thức __serialize, phương thức này sẽ xác định
những thuộc tính nào của đối tượng cần được tuần tự hóa:
<?php
class User {
public $name;
private $password;
public $email;
public function __construct($name, $password, $email) {
$this->name = $name;
$this->password = $password;
$this->email = $email;
}
public function __serialize(): array {
return [
'name' => $this->name,
'email' => $this->email,
'hash' => md5($this->password)
];
}
}
$user = new User('John', 'secret123', 'john@example.com');
echo serialize($user);
?>
Kết quả thực thi mã:
'O:4:"User":3:{s:4:"name";s:4:"John";s:5:"email";s:15:"john@example.com";s:4:"hash";s:32:"e5e9fa1ba31ecd1ae84f75caaa474f3a";}'
Ví dụ
Hãy minh họa sự khác biệt giữa __serialize và __sleep:
<?php
class Product {
public $id;
protected $price;
private $discount;
public function __sleep() {
return ['id', 'price'];
}
public function __serialize(): array {
return [
'id' => $this->id,
'price' => $this->price * (1 - $this->discount)
];
}
}
$product = new Product();
$product->id = 100;
$product->price = 50;
$product->discount = 0.1;
echo "Sleep: " . serialize($product) . "\n";
echo "Serialize: " . serialize($product);
?>
Kết quả thực thi mã:
'Sleep: O:7:"Product":2:{s:2:"id";i:100;s:5:"price";i:50;}'
'Serialize: O:7:"Product":2:{s:2:"id";i:100;s:5:"price";d:45;}'
Xem thêm
-
hàm
serialize,
chuyển đổi một giá trị thành một chuỗi có thể lưu trữ