加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 对象序列化__sleep

发布时间:2020-12-13 17:34:01 所属栏目:PHP教程 来源:网络整理
导读: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. 我理解这一点,如果有一个班级.像这样: ?phpclass Foo { public $bar = 'bar'; public $baz = '
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读