对象序列化

系统教程 行业动态 更新时间:2024-06-14 16:59:47
对象序列化__sleep(Object Serialization __sleep)

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.

更多推荐

本文发布于:2023-04-17 08:55:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/a8e8616546ca230c6d7c954841b1a229.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   序列化

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!