序列化不适用于可序列化接口

时间:2013-03-12 20:20:54

标签: php debugging serialization

 class foo implements serializable
    {
    public function serialize() {

            return serialize($this);
        }

        public function unserialize($serialized)
        {
            //Revive connection
            AbstractContent::$connection=  DatabaseHandle::getConnection();
            return unserialize($serialized);
        }
    }     


var_dump($this->object); //$this object is instance of class foo returns the exact dump of objects with correc property

     var_dump(unserialize(serialize($this->object))); //Does not dump correctly. only default property values are evaluated, constructor assigned values are ignored, computed values are ignored

2 个答案:

答案 0 :(得分:2)

根据docs

  

当数据被反序列化时,类是已知的并且是合适的   unserialize()方法被调用为构造函数而不是调用   __构造()。如果需要执行标准构造函数,可以在方法

中执行

此外,由于您在使用serialize()时没有做任何逻辑,因此您可以轻松覆盖_seelp() and __wakeup() magic methods而不是实施serializable。类似的东西:

class foo
{
    public function __wakeup() {
        // Do your logic here
    }
}
$foo = new foo();
var_dump(unserialize(serialize($foo)));

答案 1 :(得分:1)

class foo implements serilizable

应该是:

class foo implements serializable

只是一个简单的拼写错误