357 of 410 menu

The __serialize Method

The magic method __serialize is called when serializing an object with the serialize function. It should return an array of data that will be serialized. This method appeared in PHP 7.4 as an alternative to the __sleep method with more flexible control over the serialization process.

Syntax

public function __serialize(): array

Example

Let's create a class with the __serialize method that will define which object properties need to be serialized:

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

Code execution result:

'O:4:"User":3:{s:4:"name";s:4:"John";s:5:"email";s:15:"john@example.com";s:4:"hash";s:32:"e5e9fa1ba31ecd1ae84f75caaa474f3a";}'

Example

Let's demonstrate the difference between __serialize and __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); ?>

Code execution result:

'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;}'

See Also

  • the serialize function,
    which converts a value to a storable string
byenru