Recreate PHP Objects Using __set_state and var_export
This article explains how to use PHP’s __set_state()
magic method to restore and recreate objects that have been exported
using the var_export() function. You will learn how
var_export() generates an executable string representation
of an object, and how implementing the static __set_state()
method allows your classes to instantiate and populate themselves from
this exported data.
Understanding var_export() and __set_state()
The var_export() function gets structured information
about a variable. When exporting an object, it outputs code that calls a
static method named __set_state().
To recreate the object from this exported string, the target class
must implement the __set_state() magic method. This method
is called automatically when the exported PHP code is evaluated or
included.
Requirements for __set_state()
- It must be declared as
static. - It must accept a single argument: an associative
arraycontaining the exported property names and their corresponding values. - It must return an instance of the class.
Step-by-Step Implementation
Here is how to implement the __set_state() method and
use it to recreate an exported object.
1. Define the Class with __set_state()
In your class, define the static __set_state() method.
It reads the array of properties and returns a new object instance.
class User
{
public $username;
public $email;
public function __construct($username, $email)
{
$this->username = $username;
$this->email = $email;
}
// The magic method called by evaluated var_export code
public static function __set_state(array $properties)
{
$user = new self($properties['username'], $properties['email']);
return $user;
}
}2. Export the Object
Instantiate your object and pass it to var_export().
Setting the second argument of var_export() to
true returns the representation as a string instead of
outputting it directly.
$originalUser = new User('johndoe', 'john@example.com');
// Export the object to a string of PHP code
$exportedCode = var_export($originalUser, true);
echo $exportedCode;Output of $exportedCode:
User::__set_state(array(
'username' => 'johndoe',
'email' => 'john@example.com',
))3. Recreate the Object
To turn the exported code back into a live PHP object, you run the
generated code. In practice, this is usually done by writing the
exported string to a configuration file and loading it later using
include or require.
Method A: Writing to and including a file (Recommended)
// Save the exported code to a file
file_put_contents('user_cache.php', '<?php return ' . $exportedCode . ';');
// Recreate the object by including the file
$recreatedUser = include 'user_cache.php';
var_dump($recreatedUser);Method B: Using eval() (For quick execution)
// Recreate the object directly from the string using eval()
$recreatedUser = eval("return $exportedCode;");
var_dump($recreatedUser);Both methods return a fully constructed instance of the
User class with the original properties restored.