php手册说明:
它可以清理对象,并且应该返回一个数组,其中包含应该序列化的该对象的所有变量的名称。
我理解这一点,如果有一个班级。 喜欢这个:
<?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)我解释错了吗? 或者我做错了什么?
the php manual states:
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.
i understand this as, if a had a class. Like this:
<?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); ?>it would only serialize the object and the property $bar? Like this:
object(Foo)[2] public 'bar' => string 'bar' (length=3)but it returns:
object(Foo)[2] public 'bar' => string 'bar' (length=3) public 'baz' => string 'baz' (length=3)Have i interpreted it wrong? Or am i doing it wrong or what?
最满意答案
反序列化会创建对象的新实例,并且由于您的类定义初始化了该属性,因此您将获得该属性的默认值。 尝试这个:
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。
Unserializing creates a new instance of the object, and since your definition of the class initializes the attribute, you're getting a default value for it. Try this:
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);Edit: Alternatively, you can vardump($serialized) and see that there is no baz in it.
更多推荐
发布评论