Unserialize()返回空对象

时间:2016-08-10 11:02:05

标签: php oop serialization

我序列化了对象,但是在反序列化后对象是空的,我无法弄清楚我做错了什么。

这是我的代码:

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'已经通过。

有什么想法吗?

此致

2 个答案:

答案 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';
}

Live demo