本文介绍了对象序列化__sleep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

php手册指出:

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

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 03:04