note 55783 added to language.oop5.magic

From: Date: Sat, 13 Aug 2005 00:06:36 +0000
Subject: note 55783 added to language.oop5.magic
Groups: php.notes 
Request: Send a blank email to php-notes+get-93529@lists.php.net to get a copy of this message
Many of us know but many don't that, in PHP5 (and 4) saving an object in the session will *not* automatically call the magic method __sleep(), even though the actual object *is* serialized when session data is written (you can check the raw session contents). Same goes for __wakeup(). What I mean is, if you save your object in the session like this: <?php $_SESSION['myOBJ'] = $myOBJ; ?> ... then $myOBJ->__sleep() will *not* be called. To make sure the __sleep() method is called you have to manually call serialize() over the object when saving it, like this: <?php $_SESSION['myOBJ'] = serialize($myOBJ); ?> Of course, you will have to manually unserialize() it as well afterwards or $_SESSION['myOBJ'] will remain a string (duh :)) One other note, in reply to krisj1010 at gmail.com below: __sleep() handles protected/private properties very well. You should never rely on get_class_vars() to retrieve property names since this function only returns the public properties. Use the Reflection API instead for that purpose. Better yet, if you know which ones you want to save it is always faster to specify the return array manually. have a good __sleep() ---- Manual Page -- http://www.php.net/manual/en/language.oop5.magic.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+55783 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+55783&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+55783&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+55783&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+55783&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+55783&report=yes&reason=non-english Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+55783&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+55783&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#93529) next »