Taking Control of Serialization
Learn about serialization and updated magic methods introduced in PHP 8.
There are many times when native PHP data needs to be stored in a file or in a database table. The problem with current technology is that direct storage of complex PHP data, such as objects or arrays, is simply not possible, with some exceptions.
One way to overcome this limitation is to convert the object or array into a string. JSON (JavaScript Object Notation) is often chosen for this reason. Once the data has been converted into a string, it can easily be stored in any file or database. However, there is a problem with formatting objects with JSON. Although JSON is able to represent object properties well enough, it’s incapable of directly restoring the original object’s class and methods.
To address this deficiency, the PHP language includes two native functions, serialize()
and unserialize()
, that can easily convert objects or arrays into a string and restore them back to their original state. As wonderful as this sounds, there are a number of issues associated with native PHP serialization.
Before we can properly discuss the problem with the existing PHP serialization architecture, we need to have a closer look at how native PHP serialization works.
Understanding PHP serialization
When a PHP object or array needs to be saved to a non-OOP environment, such as a flat file or relational database table, serialize()
can be used to flatten an object or array into a string suitable for storage. Conversely, unserialize()
restores the original object or array.
Here is a simple example that demonstrates this concept:
<?php// Define a class named "Test".class Test {// Define public property "name" with the default value "Doug".public $name = 'Doug';// Define private property "key" with the value 12345.private $key = 12345;// Define protected property "status" as an array with values 'A', 'B', and 'C'.protected $status = ['A','B','C'];}// Create an instance of the "Test" class.$test = new Test();// Serialize the "Test" object into a string representation.$str = serialize($test);// Output the serialized string.echo $str . "\n";// Unserialize the string back into an object.$obj = unserialize($str);// Output the original object and the unserialized object for comparison.var_dump($test, $obj);?>
Let’s get into the code.
Lines 3–12: ...