我序列化了对象,但是在反序列化后对象是空的,我无法弄清楚我做错了什么。
这是我的代码:
class Foo implements \Serializable {
public $default = 10;
public $setMe;
public $removeOnSerialize = 'blah';
public function serialize()
{
unset($this->removeOnSerialze);
return serialize($this);
}
public function unserialzie($serialized)
{
$unserialized = unserialize();
$unserialize->removeOnSerialize = 'Set some value';
return $unserialized;
}
}
$obj = new Foo();
$obj->setMe = 9999;
print_r($obj) // here I have all as exepcted
$serialized = serialize($obj);
$unserialized = unserialize($serialized);
print_r($unserialized);
//object properties after deserialization
$unserialized->default === 10 // correct
$unserialized->removeOnSerialize === 'Set some value' //correct
$unserialized->setMe === NULL // wrong, it should be 9999
正如您在反序列化后看到的那样,'setMe'属性为空。 但是,'default'和'removeOnSerialize'已经通过。
有什么想法吗?
此致
答案 0 :(得分:2)
正如评论部分已经提到的那样,你不应该从unserialize
方法返回任何内容。它必须设置对象的值。
您可能通过从serialize
方法调用同一类的实例上的serialize
来获得堆栈溢出。
我想你可以这样做:
class Foo implements \Serializable
{
public $default = 10;
public $setMe;
public $removeOnSerialize = 'blah';
public function serialize()
{
unset($this->removeOnSerialze);
return serialize($this->getData());
}
public function unserialize($serialized)
{
foreach (unserialize($serialized) as $key => $value) {
$this->$key = $value;
}
$this->removeOnSerialize = 'Set some value';
}
protected function getData()
{
return get_object_vars($this);
}
}
答案 1 :(得分:0)
使用自定义序列化,您有责任提供要保存到serialize()
的内容,并负责解析unserialize()
您可以将serialize
更改为:
public function serialize(){
$toSave = ['setMe'=>$this->setMe];
return serialize($toSave);
}
这样,removeOnSerialize
不会保存。到unserialize
你可以做到
public function unserialize($data){
$data = unserialize($data);
$this->setMe = $data['setMe'];
$this->removeOnSerialize = 'Set some value';
}