原文地址:[url="http://hi.baidu.com/hywmickey/item/61569e4bbeb9d10fc1161375"]侯永伟的空间[/url]
<?php
//<!--本实例有三个文件组成:class.php serialize.php unserialize.php-->
//<!--class.php-->
class Person
{
protected $name;
protected $age;
protected $sex;
function __construct($name="",$age="",$sex="")
{
$this->name=$name;
$this->age=$age;
$this->sex=$sex;
}
function __destruct()
{
echo $this->name."再见<br />";
}
function __sleep()//序列化是调用
{
$arr=array("name","sex");//串行化部分属性
return $arr;
}
function __wakeup()//反序列化时调用
{
//echo "###################";
return $this->name="四李";
return $this->age=50;
}
function say()
{
echo "我的名字是:".$this->name.",我的年龄是:".$this->age.",我的性别是:".$this->sex."<br />";
}
function eat()
{
echo $this->name."在吃饭<br />";
}
function __toString()
{
}
}
?>
<?php
//<!--serialize.php-->
include "class.php";
$p1=new Person("张三",20,"男");
$str=serialize($p1);
$file=fopen("tmp.txt","w");
fwrite($file,$str);
fclose($file);
?>
<?php
<!--unserialize.php-->
include "class.php";
$file=fopen("tmp.txt","r");
$str=fread($file,filesize("tmp.txt"));
fclose($file);
$p=unserialize($str);
$p->say();
?>