note 59330 modified in function.serialize by danbrown

From: Date: Mon, 20 Jun 2011 15:26:03 +0000
Subject: note 59330 modified in function.serialize by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-180762@lists.php.net to get a copy of this message
Here is an example of a base class to implement object persistence using serialize and unserialize: <?php class Persistent { var $filename; /**********************/ function Persistent($filename) { $this->filename = $filename; if(!file_exists($this->filename)) $this->save(); } /**********************/ function save() { if($f = @fopen($this->filename,"w")) { if(@fwrite($f,serialize(get_object_vars($this)))) { @fclose($f); } else die("Could not write to file ".$this->filename." at Persistant::save"); } else die("Could not open file ".$this->filename." for writing, at Persistant::save"); } /**********************/ function open() { $vars = unserialize(file_get_contents($this->filename)); foreach($vars as $key=>$val) { eval("$"."this->$key = $"."vars['"."$key'];"); } } /**********************/ } ?> When an object is extended from this one it can be easily saved and re-opened using it's own methods as follows: <? class foo extends Persistent { var $counter; function inc() { $this->counter++; } } $fooObj = new $foo; $foo->open(); print $foo->counter; // displays incrementing integer as page reloads $foo->inc(); $foo->save(); ?> --was-- Here is an example of a base class to implement object persistence using serialize and unserialize: <? class Persistent { var $filename; /**********************/ function Persistent($filename) { $this->filename = $filename; if(!file_exists($this->filename)) $this->save(); } /**********************/ function save() { if($f = @fopen($this->filename,"w")) { if(@fwrite($f,serialize(get_object_vars($this)))) { @fclose($f); } else die("Could not write to file ".$this->filename." at Persistant::save"); } else die("Could not open file ".$this->filename." for writing, at Persistant::save"); } /**********************/ function open() { $vars = unserialize(file_get_contents($this->filename)); foreach($vars as $key=>$val) { eval("$"."this->$key = $"."vars['"."$key'];"); } } /**********************/ } ?> When an object is extended from this one it can be easily saved and re-opened using it's own methods as follows: <? class foo extends Persistent { var $counter; function inc() { $this->counter++; } } $fooObj = new $foo; $foo->open(); print $foo->counter; // displays incrementing integer as page reloads $foo->inc(); $foo->save(); ?> http://php.net/manual/en/function.serialize.php

« previous php.notes (#180762) next »