Improved support for serializing objects (for sessions etc)

From: Date: Thu, 16 Mar 2000 02:30:23 +0000
Subject: Improved support for serializing objects (for sessions etc)
Groups: php.version4 
Request: Send a blank email to php-version4+get-12207@lists.php.net to get a copy of this message
hi, just implemented _sleep_() and _wakeup_() in serialize()/ unserialize(). how it works: when an object is serialized() *and* it implements the _sleep_() method the _sleep_() method is called. it *must* return an array of the names of *all* instance variables to be serialized! only those will be put in the serialized data-stream. when an object is unserialized and it implements a _wakeup_() method this method will be called *after* all the serialized data is restored. that way the coder can reopen files, reestablish db-links etc. see attached sample on how it works. this should allow one to store db-connections in sessions etc. would that be useful for future versions of phplib, kris? do we want to put something like it into wddx, andrei? should it be in the docs, egon? tc BTW: if your class does not have _sleep_() and/or _wakeup_() calls nothing bad will happen, just the "old" behaviour. <? error_reporting(-1); class test { function test($filename=NULL,$mode=NULL) { echo "constructor called\n"; $this->filename = $filename; $this->mode = $mode; // we could call $this->_wakeup() instead! if ($this->filename && $this->mode) { $this->fd = fopen($this->filename,$this->mode); } } function _sleep_() { echo "sleep\n"; // return list of instance-variables to be serialized return array("filename","mode"); } function _wakeup_() { echo "wakeup\n"; // all serialized instance variables are set now, inititalize the non-serializeable ones if ($this->filename && $this->mode) { $this->fd = fopen($this->filename,$this->mode); } } function _string_value_() { return "hallo i'm using $this->filename\n"; } } $a = new test("/tmp/thies.tcsh","r"); echo $a; var_dump($a); $b = serialize($a); var_dump($b); $a = unserialize($b); var_dump($a); ?> -- Thies C. Arntzen "One Big-Mac, Small Fries and a Coke!" Digital Collections Phone +49 40 235350 Fax +49 40 23535180 Hammerbrookstr. 93 20097 Hamburg / Germany

« previous php.version4 (#12207) next »