358 of 410 menu

The __unserialize Method

The __unserialize method is automatically called during object deserialization using the unserialize function. It accepts an array with data that was previously prepared by the __serialize method.

Syntax

public function __unserialize(array $data): void

Example

Let's create a class with __serialize and __unserialize methods:

<?php class User { private $name; private $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } public function __serialize(): array { return ['name' => $this->name, 'age' => $this->age]; } public function __unserialize(array $data): void { $this->name = $data['name']; $this->age = $data['age']; } public function getInfo() { return $this->name . ', ' . $this->age; } } $user = new User('John', 30); $serialized = serialize($user); $unserialized = unserialize($serialized); echo $unserialized->getInfo(); ?>

Code execution result:

'John, 30'

Example

Using __unserialize with private properties:

<?php class Product { private $id; private $price; public function __construct($id, $price) { $this->id = $id; $this->price = $price; } public function __serialize(): array { return ['id' => $this->id, 'price' => $this->price]; } public function __unserialize(array $data): void { $this->id = $data['id']; $this->price = $data['price']; } public function getPrice() { return $this->price; } } $product = new Product(123, 99.99); $serialized = serialize($product); $unserialized = unserialize($serialized); echo $unserialized->getPrice(); ?>

Code execution result:

99.99

See Also

  • the __serialize method,
    which prepares an object for serialization
  • the serialize function,
    which converts an object to a string
byenru