Make simple data local storage with PHP serialization and deserialization
The following program can be used as a tool class
/** * Use PHP serialization and deserialization to make simple data local storage*/ classObjectdb {Private Static $db; //successful return of the Objectdb object, no need to use the new//directory outside to write file permissions Public functionDefaultdb ($dbname= './default.db ') { self::$db=$dbname; if(file_exists($dbname)) { return NewObjectdb (); } $ret=file_put_contents($dbname,Serialize(Array())); if($ret> 0) { return NewObjectdb (); } return false; } //Add data key,value or update Public functionSetvalueforkey ($key,$value) { $arrdata=$this-Getdbarray (); $arrdata[$key] =$value; return $this->setdbarray ($arrdata); } //Delete data from the specified key Public functionRemovevalueforkey ($key) { $arrdata=$this-Getdbarray (); unset($arr[$key]); } //gets the data for the specified key Public functionGetvalueforkey ($key) { $arrdata=$this-Getdbarray (); return $arrdata[$key]; } //get all the data Public functionGetAll () {$arrdata=$this-Getdbarray (); return $arrdata; } //get all the keys Public functionGetallkey () {$arrdata=$this-Getdbarray (); return Array_keys($arrdata); } //Empty DB data Public functionCleardb () {$ret=file_put_contents(Self::$db,Serialize(Array())); return $ret; } //Private Get Private functionGetdbarray () {$rdata=file_get_contents(Self::$db); return unserialize($rdata); } //Private Set Private functionSetdbarray ($arr) { $ret=file_put_contents(Self::$db,Serialize($arr)); if($ret> 0) { return true; }Else { return false; } } }
The test code is as follows
//Test $dbhandle= Objectdb::Defaultdb (); if(!$dbhandle) { Echo"Init failure!"; Exit(); } Echo"Start <br>"; Var_dump($dbhandle-getAll ()); Echo"<br>add 1 <br>"; $dbhandle->setvalueforkey ("Baidu", "www.baidu.com"); $dbhandle->setvalueforkey ("QQ", "www.qq.com")); $dbhandle->setvalueforkey ("Taobao", "www.taobao.com"); Var_dump($dbhandle-getAll ()); Echo"<br>mod 1 <br>"; $dbhandle->setvalueforkey ("Baidu", "http://www.baidu.com"); Var_dump($dbhandle-getAll ()); Echo"<br>get 1 <br>"; Echo $dbhandle->getvalueforkey ("Baidu"); Echo"<br>get 1 <br>"; Var_dump($dbhandle-Getallkey ()); Echo"<br>clear 1 <br>"; $dbhandle-Cleardb (); Echo"<br>get 1 <br>"; Var_dump($dbhandle->getall ());
Make simple data local storage with PHP serialization and deserialization