php中对象的串行化
我们大家有知道php串行化可以把变量包括对象,转化成连续bytes数据,你可以将串行化后的变量存在一个文件里或在网络上传输,然后再反串行化还原为原来的数据。文章这里就PHP串行化为大家详细的介绍。你在反串行化类的对象之前定义的类,PHP可以成功地存储其对象的属性和方法. 有时你可能需要一个对象在反串行化后立即执行。为了这样的目的,PHP会自动寻找__sleep和__wakeup方法。
当一个对象被PHP串行化,PHP会调用__sleep方法(如果存在的话). 在反串行化一个对象后,PHP 会调用__wakeup方法. 这两个方法都不接受参数. __sleep方法必须返回一个数组,包含需要串行化的属性. PHP会抛弃其它属性的值。如果没有__sleep方法,PHP将保存所有属性。
<?php/**
* @Authors peng--jun
* @Email 1098325951@QQ.com
* @Date 2016-01-23 14:40:38
* @Linkhttp://www.cnblogs.com/xs-yqz/* @version $Id$
==========================================*/header("Content-type: text/html; charset=UTF-8");classPerson{PRivate$name;private$sex;private$age;
function __construct($name,$age,$sex){
$this->name =$name;
$this->age =$age;
$this->sex =$sex;
}
function say(){
echo"我的名字:".$this->name."性别为:".$this->sex."年龄为:".$this->age;
}//在类中添加此方法,在串行化的时候自动调用并返回数组function __sleep(){
$arr= array("name","age");//数组中的成员$name和$age将被串行化,成员$sex则将被忽略。return($arr);//使用__sleep()方法的时候必须返回一个数组。}//在反串行化对象时自动调用该方法,没有参数也没有返回值function __wakeup(){
$this->age =40;//在重新组织对象的时候,为新对象中的$age属性重新赋值}
}
$person1=newPerson("张三",20,"男");
$person1_string=serialize($person1);
echo $person1_string."<br />";//反串行化对象,并自动调用了__wakeup()方法重新为独享中的age赋值。$person2 =unserialize($person1_string);
$person2->say();?>
输出的结果为:
O:6:"Person":2:{s:12:"Personname";s:6:"张三";s:11:"Personage";i:20;}
我的名字:张三性别为: 年龄为:40
2.将串行化的字符串保存到文件中,从文件中读取字符串,反串性化实例。
header("Content-type: text/html; charset=UTF-8");classPerson{private$name;private$sex;private$age;
function __construct($name,$age,$sex){
$this->name =$name;
$this->age =$age;
$this->sex =$sex;
}
function say(){
echo"我的名字:".$this->name."性别为:".$this->sex."年龄为:".$this->age;
}
}
$person1=newPerson("张三",21,"男");
$person1_string=serialize($person1);
file_put_contents("file.txt", $person1_string);
header("Content-type: text/html; charset=UTF-8");classPerson{private$name;private$sex;private$age;
function __construct($name,$age,$sex){
$this->name =$name;
$this->age =$age;
$this->sex =$sex;
}
function say(){
echo"我的名字:".$this->name."性别为:".$this->sex."年龄为:".$this->age;
}
}
$person2_string= file_get_contents("file.txt");
$person2=unserialize($person2_string);//反串性化重新形成对象$person2.$person2->say();?>