My PHP code is here :
class test {
public $a = 'a';
public $b = 'b';
public $c = 'c';
}
$a = new test();
unset($a->a);
$b = serialize($a);
$c = unserialize($b);
var_dump($a, $b, $c);
Why does $c
contain the property a
?
My PHP code is here :
class test {
public $a = 'a';
public $b = 'b';
public $c = 'c';
}
$a = new test();
unset($a->a);
$b = serialize($a);
$c = unserialize($b);
var_dump($a, $b, $c);
Why does $c
contain the property a
?
unserialize
creates and initialises a new instance of the class (although it doesn't call the constructor), and then maps any property values from the serialized string over the top. Because you're unsetting the property entirely there isn't a value to map back over the default, and so it stays set in your new object.
If you set the property to null rather than unsetting it then it will still be stored in the serialized copy, and the behaviour should end up the same as you intended.
$setToNull = new test;
$unset = new test;
$setToNull->a = null;
unset($unset->a);
var_dump(unserialize(serialize($setToNull)), unserialize(serialize($unset)));
object(test)#3 (3) { ["a"]=> NULL ["b"]=> string(1) "b" ["c"]=> string(1) "c" }
object(test)#4 (3) { ["a"]=> string(1) "a" ["b"]=> string(1) "b" ["c"]=> string(1) "c" }
(The difference is that the restored object will still have the a
property set to null, which isn't quite the same as having it unset, but should behave the same in most situations)
As a more complicated solution (or if this doesn't match the behaviour you actually expect) then you might be able to make use of PHP's __sleep
and __wakeup
magic methods on your class, which give you finer-grained control of what happens when an object is serialized/unserialized.
When you call unserialize a new object will be created. It's not exactly the same object.
Your class have default values so when you unserialize an object and you don't have $a property being set then a default value will be used.
To see the difference check this code
class test {
public $a = 'a';
public $b = 'b';
public $c = 'c';
}
$a = new test();
$a->a= 'property'; // set a to "property"
unset($a->a); // remove a
$b = serialize($a);
$c = unserialize($b); // there is no "a" property set so default value will be used
var_dump($a, $b, $c);
If you remove default value from public $a = 'a';
then it'll be null
class test {
public $a;
public $b = 'b';
public $c = 'c';
}
$a = new test();
$a->a= 'property';
unset($a->a);
$b = serialize($a);
$c = unserialize($b);
echo '<pre>';
var_dump($a, $b, $c);