note 115449 deleted from language.oop5.serialization by salathe

From: Date: Mon, 04 Aug 2014 08:48:03 +0000
Subject: note 115449 deleted from language.oop5.serialization by salathe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-200103@lists.php.net to get a copy of this message
Note Submitter: me at iabdullah dot info ---- In case you're reading the official book that written by Rasmus and the other authors, Here is the serialization and unserialization Example (6-3) since it is written in the old fashion way (using session_register() ..) and has some typos. (Log.php) an object class, Log, provides two useful methods: write() to append a message to the logfile, and read() to fetch the current contents of the logfile. It uses __wakeup() to reopen the logfile and __sleep() to close the logfile. <?php class Log { private $filename; private $fh; public function __construct ($fn) { $this->filename = $fn; $this->open(); } public function open () { $this->fh = fopen ($this->filename,'a') or die ("Can't open {$this->filename} !"); } public function write ($note) { fwrite($this->fh, "{$note}\n"); } public function read () { return join ('', file($this->filename)); } public function __wakeup() { $this->open(); } public function __sleep () { fclose ($this->fh); return array("filename"); } } ?> Store the Log class definition in a file called Log.inc. (front.php) The front.php uses the Log class and PHP sessions to create a persistent log variable, $Logger. <?php include_once ("Serialization.php"); session_start(); ?> <html> <head> <title>Front Page</title> </head> <body> <?php $now = strftime("%c"); if (!isset($_SESSION['Logger'])) { $l = new Log ("tmp/persistent_log"); $_SESSION['Logger'] = $l; $l->write("Created {$now}"); echo ("<p> Created Session and Persistent Log File </p>"); } else { $_SESSION['Logger']->write("Viewed Page 1 at {$now}"); echo "<p> The Log content : </p>"; echo nl2br($_SESSION['Logger']->read()); } ?> <a href="next.php"> Move the next Page !!</a> </body> </html> (next.php) The file next.php shows , an HTML page, Following the link from the front page to this page triggers the loading of the persistent object $logger. The __wakeup() call reopens the logfile so the object is ready to be used. <?php include_once ("Serialization.php"); session_start(); ?> <html> <head> <title>Next Page</title> </head> <body> <?php $now = strftime("%c"); $logger = $_SESSION['Logger']; $logger->write("Viewed Page 2 at {$now}"); echo "<p> The Log content : </p>"; echo nl2br($logger->read()); ?> </body> </html> Create folder 'tmp' and file 'persistent_log' to avoid getting fopen warning error message.

« previous php.notes (#200103) next »