note 61418 deleted from function.serialize by aharvey

From: Date: Tue, 06 Nov 2012 02:10:28 +0000
Subject: note 61418 deleted from function.serialize by aharvey
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-191770@lists.php.net to get a copy of this message
Note Submitter: Neil Green ---- Are you trying to store and retrieve an object from session and it's disappearing? Did you look at what the serialized object looked like and saw a strange "N;"? Does the object you're trying to serialize or store in a session define the __call magic method? Here's the problem: If you try to serialize an object that uses the __call magic method you are not going to be able to unserialize it. Here's what happens: 1. You try to serialize an object with the __call magic method defined 2. The magic method __sleep is always called on an object being serialized 3. __call traps __sleep because it's not defined 4. __call does not respond to __sleep with what is expected: an array of properties to serialize The solution is defining a __sleep method that returns what it's supposed to when you define a __call: <? // This is just a handy debug function function show( $object ){ echo "<pre>" . print_r( $object, true ) . "</pre>"; } class foo { private $private = "private value"; public $public = "public value"; public function __call( $method, $arguments ) { } // Remove this and serialise/unserialse won't work public function __sleep() { return array_keys( get_object_vars( $this ) ); } } $foo = new Foo(); show( $foo ); $serializedFoo = serialize( $foo ); show( $serializedFoo ); show( unserialize( $serializedFoo ) ); ?> BTW, I'm using PHP Version 5.0.4 on Windows. To the editor: This post may be useful under the __call, __unserialise, and session pages as well.

« previous php.notes (#191770) next »