我有一個像下面這樣的對象樹,我需要序列化並存儲在文件系統上。我需要具有所有類屬性的完整層次結構,稍後我將反序列化並還原類層次結構。PHP序列化對象樹
class X implements \Serializable {
private $x1;
public function serialize() {
return serialize(get_class_vars(get_class($this)));
}
public function unserialize($data) {
$values = unserialize($data);
foreach ($values as $key => $value) {
$this->$key = $value;
}
}
}
class A implements \Serializable {
private $a1;
private $a2;
// type of a3 is class X!
protected $a3;
public function serialize() {
return serialize(get_class_vars(get_class($this)));
}
public function unserialize($data) {
$values = unserialize($data);
foreach ($values as $key => $value) {
$this->$key = $value;
}
}
}
class B extends A implements \Serializable {
private $b1;
private $b2;
public function serialize() {
// $base = parent::serialize();
return serialize(get_class_vars(get_class($this)));
}
public function unserialize($data) {
$values = unserialize($data);
foreach ($values as $key => $value) {
$this->$key = $value;
}
}
}
class C extends A implements \Serializable {
private $c1;
private $c2;
public function serialize() {
// $base = parent::serialize();
return serialize(get_class_vars(get_class($this)));
}
public function unserialize($data) {
$values = unserialize($data);
foreach ($values as $key => $value) {
$this->$key = $value;
}
}
}
子類可以序列化本身,而是基類,我不知道,我怎麼能結合序列化的數據。此外,我從文件系統獲取序列化的數據,但我不知道,我會得到哪個子類。 PHP的unserialize()是否創建了正確的類實例?它也應該初始化基類A.
我該如何解決這個問題?
也許我可以使用var_dump()輸出,但我怎麼可以將它存儲到一個變量?