The magic methods carry the serialized form, and the interface methods
delegate to them, so that a single representation serves both.
<?php
class Task implements Serializable
{
private $label;
public function __construct($label)
{
$this->label = $label;
}
public function __serialize(): array
{
return ['label' => $this->label];
}
public function __unserialize(array $data): void
{
$this->label = $data['label'];
}
// Never called as of PHP 7.4.0
public function serialize()
{
return serialize($this->__serialize());
}
// Still called as of PHP 7.4.0, for data written before it
public function unserialize($data)
{
$this->__unserialize(unserialize($data));
}
}
var_dump(serialize(new Task('deploy')));
?>
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
string(47) "C:4:"Task":31:{a:1:{s:5:"label";s:6:"deploy";}}".