Kaedah __serialize
Kaedah ajaib __serialize dipanggil semasa penyeseralan objek
dengan fungsi serialize. Ia harus mengembalikan array data yang
akan diserikan. Kaedah ini muncul dalam PHP 7.4 sebagai alternatif
kepada kaedah __sleep dengan kawalan proses penyeseralan yang lebih fleksibel.
Sintaks
public function __serialize(): array
Contoh
Mari buat kelas dengan kaedah __serialize yang akan menentukan
sifat objek mana yang perlu diserikan:
<?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);
?>
Hasil pelaksanaan kod:
'O:4:"User":3:{s:4:"name";s:4:"John";s:5:"email";s:15:"john@example.com";s:4:"hash";s:32:"e5e9fa1ba31ecd1ae84f75caaa474f3a";}'
Contoh
Mari tunjukkan perbezaan antara __serialize dan __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);
?>
Hasil pelaksanaan kod:
'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;}'
Lihat juga
-
fungsi
serialize,
yang menukar nilai kepada rentetan yang boleh disimpan