本文实例讲述了php中串行化用法。分享给大家供大家参考,具体如下:
功能:串行化用于对对象的存储或者传输,通过反串行化得到这个对象。
1. person.class.php:
<?php
/*
作者 : shyhero
*/
class person{ //声明一个person类
public $age;
private $name;
protected $sex;
public function __construct($age="",$name="",$sex=""){
$this -> age = $age;
$this -> name = $name;
$this -> sex = $sex;
}
public function say(){
return $this -> age." ".$this -> name." ".$this -> sex;
}
function __sleep(){ //指定串行化时能提取的成员属性,没有参数,但是必须返回一个数组
$arr = array("age","name");
return $arr;
}
function __wakeup(){ //指定反串行化时,提取出来的值
$this -> sex = "woman";
}
}
2. 串行化代码
<?php
require("./person.class.php");
$p = new person(21,"du","man"); //定义person类对象
$pstring = serialize($p); //对对象进行串行化
file_put_contents("./file.txt",$pstring);//存到文件里
3. 反串行化代码
<?php
require("./person.class.php");//反串行化时,也要包含原类
$pstring = file_get_contents("./file.txt");//从文件中取出串行化的值
$p = unserialize($pstring);//进行反串行化
var_dump($p); //这个 $p就是之前那个串行化的对象,一样用,但是里面的值被我改了
以上就是php中串行化用法示例详解的内容。