4

the php manual states:

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

?>

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

Have i interpreted it wrong? Or am i doing it wrong or what?

2 Answers 2

6

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

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

2
  • Thank you, you made it really easy to understand.
    – Esben
    Mar 1, 2011 at 22:38
  • Or move initialization in constructor, since unserialize won't call constructor and your baz might remain uninitialized. Jul 13, 2021 at 13:06
1

You're defining an initial value of 'baz' for the $baz property, so when you unserialize, PHP recreated baz with that default value despite the fact that it's not part of the serialized object. If you changed the value of baz before serializing, then serialize/unserialize, it will reset baz to that default value of 'baz', rather than to the value you had changed it to.

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
  • Thank you, you made it really easy to understand.
    – Esben
    Mar 1, 2011 at 22:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.