对象序列化__sleep [英] Object Serialization __sleep

查看:61
本文介绍了对象序列化__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.

我理解为,如果一个人上过课.像这样:

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);

?>

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

it would only serialize the object and the property $bar? Like this:

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

但它返回:

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?

推荐答案

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

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);

或者,您可以存储($ serialized)并查看其中没有baz.

Alternatively, you can vardump($serialized) and see that there is no baz in it.

这篇关于对象序列化__sleep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆