Introducing the Serializable Interface
Learn about the issues associated with the Serializable interface and how to handle them using new magic methods introduced in PHP 8.
We'll cover the following...
In order to facilitate the serialization of objects, the Serializable interface was added to the language beginning with PHP 5.1. The idea behind this interface was to provide a way of identifying objects that had the ability to serialize themselves. In addition, the methods specified by this interface were designed to provide some degree of control over object serialization.
As long as a class implements this interface, developers are assured that two methods are defined: serialize() and unserialize(). Here is the interface definition:
interface Serializable {public serialize () : string|nullpublic unserialize (string $serialized) : void}
Any class that implements this interface has its custom serialize() and unserialize() methods automatically invoked during native serialization or unserialization. To illustrate this technique, consider the following example:
Let’s get into the code.
Lines 3–7: First, we define a class that implements the
Serializableinterface. The class defines three properties: two of type string, the other representing date and time.Lines 11–30: We then define a custom
serialize()method that initializes the date and time before serializing the object’s properties. Theunserialize()method restores values to all ...