gpt4 book ai didi

php - 对象序列化 __sleep

转载 作者:可可西里 更新时间:2023-10-31 22:15:50 26 4
gpt4 key购买 nike

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.

我的理解是,如果有一个类(class)。像这样:

<?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。

关于php - 对象序列化 __sleep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5161065/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com