Serializing __sleep objects

the php manual says:

It can clear an object and must return an array with the names of all the variables of this object that must 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);

?>

will it serialize the object and the $ bar property? 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)

Did I misunderstand this? Or am I doing it wrong or what?

+3
source share
2 answers

Unserializing creates a new instance of the object, and since your class definition initializes the attribute, you get a default value for it. Try the following:

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.

+5
source

"baz" $baz, , , PHP baz , , . baz , /unserialize, reset baz "baz", , .

class Foo {
    public $bar = 'bar';

    public $baz = 'baz';

    public function __sleep() {
        return array('bar');
    }
}

$obj = new Foo();
$obj->baz = 'newbaz';

var_dump($obj);

$serialized = serialize($obj);
$unserialized = unserialize($serialized);
var_dump($unserialized);
+1

Source: https://habr.com/ru/post/1795619/


All Articles