php – 对象序列化__sleep

php手册说明:

It can clean up the object and is
supposed to return an array with the
names of all variables of that object
that should be serialized.

我理解这一点,如果有一个班级.像这样:

<?php

class Foo {

    public $bar = 'bar';

    public $baz = 'baz';

    public function __sleep() {
        return array('bar');
    }

}

$obj = new Foo();
$serialized = serialize($obj);
$unserialized = unserialize($serialized);

var_dump($unserialized);

?>

它只会序列化对象和属性$bar?像这样:

object(Foo)[2]
  public 'bar' => string 'bar' (length=3)

但它返回:

object(Foo)[2]
  public 'bar' => string 'bar' (length=3)
  public 'baz' => string 'baz' (length=3)

我解释错了吗?或者我做错了什么?

反序列化会创建对象的新实例,并且由于您的类定义初始化了该属性,因此您将获得该属性的默认值.试试这个:

class Foo {
    public $bar;
    public $baz;
    public function __sleep()
    {
        return array('bar');
    }
}

$obj = new Foo();
$obj->bar = 'bar';
$obj->baz = 'baz';
$serialized = serialize($obj);
$unserialized = unserialize($serialized);
var_dump($unserialized);

编辑:或者,您可以vardump($serialized)并看到其中没有baz.

相关文章
相关标签/搜索