I ran into a rather difficult problem to solve objects that implement the interface Serializable. Take an example:
class A {
public $b;
}
class B {
public $a;
}
$a = new A;
$b = new B;
$a->b = $b;
$b->a = $a;
echo serialize($a);
echo serialize($b);
$a = unserialize(serialize($a));
var_export($a === $a->b->a);
In this example, we see that when using the built-in PHP serialization function (regardless of whether we use the function __sleep()), cross-references between Aand Bare preserved ( r:1;).
However, if we want to ensure that the Serializable interface is used, a problem arises:
class A implements Serializable {
public $b;
public function serialize() { return serialize($this->b); }
public function unserialize($s) { $this->b = unserialize($s); }
}
class B implements Serializable {
public $a;
public function serialize() { return serialize($this->a); }
public function unserialize($s) { $this->a = unserialize($s); }
}
$a = new A;
$b = new B;
$a->b = $b;
$b->a = $a;
echo serialize($a);
Since each serialization of objects is controlled independently, there is no global way to see if an object has already been serialized; there is no link to it. Then the functions serialize()are called in an infinite loop.
? , serialize()?