note 98963 modified in language.oop5.magic by danbrown

From: Date: Sun, 18 Jul 2010 23:27:34 +0000
Subject: note 98963 modified in language.oop5.magic by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-170961@lists.php.net to get a copy of this message
Note a common pitfall when using __wakeup. If you unserialize a datastructure, you may not rely on the parent object to have been fully unserialized by the time __wakeup is called. Example <?php class A { public $b; public $name; } class B extends A { public $parent; public function __wakeup() { var_dump($parent->name); } } $a = new A(); $a->name = "foo"; $a->b = new B(); $a->b->parent = $a; $s = serialize($a); $a = unserialize($s); ?> Expected output: "foo". Actual output: NULL. Reason: $b is unserialized before $name. By the time B::__wakeup is called, $a->name does not yet have a value. So be aware that the order in which your class variables are defined is important! You need to manually order them by dependencies - or write a __sleep function and order them by depencies there. (Currently I can't tell which option I hate more) --was-- Note a common pitfall when using __wakeup. If you unserialize a datastructure, you may not rely on the parent object to have been fully unserialized by the time __wakeup is called. Example class A { public $b; public $name; } class B extends A { public $parent; public function __wakeup() { var_dump($parent->name); } } $a = new A(); $a->name = "foo"; $a->b = new B(); $a->b->parent = $a; $s = serialize($a); $a = unserialize($s); Expected output: "foo". Actual output: NULL. Reason: $b is unserialized before $name. By the time B::__wakeup is called, $a->name does not yet have a value. So be aware that the order in which your class variables are defined is important! You need to manually order them by dependencies - or write a __sleep function and order them by depencies there. (Currently I can't tell which option I hate more) http://php.net/manual/en/language.oop5.magic.php

« previous php.notes (#170961) next »