Taking Control of Serialization

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:

Get hands-on with 1200+ tech skills courses.