php的序列化&反序列化对与一些大文件的压缩操作,读写操作十分有用。
一个简单的序列化案例
同时用到了序列化与反序列化函数,二者在被调用时会分别自己调用对应的函数,__sleep 以及__wakeup.
<?php
/*
__sleep和__wakeup练习题:
故事:一个果农生产了很多水果种类,于是需要把一个买家指定的种类寄给他,生产的日期和寄给买家的日期
水果类(几个成员,苹果种类,雪梨种类,西瓜种类)
----------------------------
fruit.class.php(__sleep和__wakeup)
buy.php
pass.php
/三个文件都同时写在index.php里
*/
class Fruit{
private $apple;
private $banana;
private $xigua;
private $xuanli;
private $date;
function __construct($apple, $banana, $xigua, $xueli, $date ="1.26"){
$this->apple = $apple;
$this->banana = $banana;
$this->xigua = $xigua;
$this->xueli = $xueli;
$this->date = $date;
}
function getInfo(){
echo "信息如下:".$this->apple."&&&".$this->banana."&&&".$this->xigua."&&&".$this->xueli."<br />生产日期"."&&&".$this->date;
}
function __sleep(){
$info = array("apple","xueli","xigua","date");
return $info;
}
function __wakeup(){
$this->date = "2.20";
}
}
//1
//$fruit = new Fruit("苹果","香蕉","西瓜","雪梨");
//$fruit->getInfo();
//2
echo "<br />拥有的水果:<br />";
$fruit = new Fruit("苹果","香蕉","西瓜","雪梨");
$str = serialize($fruit);
$fruit->getInfo();
file_put_contents('fruit.txt',$str);
echo "<hr />";
$stri =file_get_contents('fruit.txt');
$shuiguo = unserialize($stri);
$shuiguo->getInfo();