360 of 410 menu

The __set_state Method

The __set_state method is static and is called automatically when using the var_export function on an object. It should return a new instance of the class with restored properties. This method is useful for object serialization and deserialization.

Syntax

public static function __set_state(array $properties): object

Example

Let's create a class and implement the __set_state method in it:

<?php class MyClass { public $prop1; public $prop2; public function __construct($val1, $val2) { $this->prop1 = $val1; $this->prop2 = $val2; } public static function __set_state($array) { return new self($array['prop1'], $array['prop2']); } } $obj = new MyClass('a', 'b'); $exported = var_export($obj, true); eval('$newObj = ' . $exported . ';'); var_dump($newObj); ?>

Code execution result:

object(MyClass)#2 (2) { ["prop1"]=> string(1) "a" ["prop2"]=> string(1) "b" }

Example

Using __set_state with private properties:

<?php class PrivateClass { private $secret; public function __construct($value) { $this->secret = $value; } public static function __set_state($array) { $obj = new self($array['secret']); return $obj; } } $privateObj = new PrivateClass('12345'); $exported = var_export($privateObj, true); eval('$newPrivateObj = ' . $exported . ';'); var_dump($newPrivateObj); ?>

Code execution result:

object(PrivateClass)#2 (1) { ["secret":"PrivateClass":private]=> string(5) "12345" }

See Also

  • the var_export function,
    which exports a variable to a string
  • the __sleep method,
    which is called before object serialization
  • the __wakeup method,
    which is called upon object deserialization
byenru