|
The Serializable interfaceIntroductionInterface for customized serializing. Classes that implement this interface no longer support __sleep() and __wakeup(). The serialize method is called whenever an instance needs to be serialized. This does not invoke __destruct or have any other side effect unless programmed inside the method. When the data is unserialized the class is known and the appropriate unserialize method is called as a constructor instead of calling __construct. The constructor can be called from within the unserialize method if desired. Warning
As of PHP 8.1.0, a class which implements Serializable without also implementing __serialize() and __unserialize() will generate a deprecation warning. New code should use the __serialize() and __unserialize() magic methods instead, available as of PHP 7.4.0. When a class declares both them and this interface, serialize always uses __serialize() and never reaches Serializable::serialize. Unserializing is decided by the format of the data instead: a payload written by PHP 7.4.0 or later is read by __unserialize(), one written before it is still read by Serializable::unserialize. Implementing Serializable therefore remains of use for reading such older payloads, and for satisfying a Serializable type declaration; declaring all four methods covers every case, and avoids the deprecation notice.
Interface synopsis
Serializable
/* Methods */
public stringnull Serializable::serialize()
public void Serializable::unserialize(string
$data)ExamplesExample #1 Supporting PHP 7.1.0 through 7.3.0 The magic methods carry the serialized form, and the interface methods delegate to them, so that a single representation serves both. The above example will output:
string(40) "O:4:"Task":1:{s:5:"label";s:6:"deploy";}"
Prior to PHP 7.4.0, the same code serializes through the interface
instead, and outputs
|