- 相關(guān)推薦
PHP中串行化用法
串行化大概就是把一些變量轉(zhuǎn)化成為字符串的字節(jié)流的形式,這樣比較容易傳輸、存儲(chǔ)。當(dāng)然,關(guān)是傳輸存儲(chǔ)沒(méi)有什么,關(guān)鍵是變成串的形式以后還能夠轉(zhuǎn)化回來(lái),而且能夠保持原來(lái)數(shù)據(jù)的結(jié)構(gòu)。以下是小編為大家搜索整理的PHP中串行化用法,希望能給大家?guī)?lái)幫助!更多精彩內(nèi)容請(qǐng)及時(shí)關(guān)注我們應(yīng)屆畢業(yè)生考試網(wǎng)!
1. Person.class.php:
*/
class Person{ //聲明一個(gè)Person類(lèi)
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(){ //指定串行化時(shí)能提取的成員屬性,沒(méi)有參數(shù),但是必須返回一個(gè)數(shù)組
$arr = array("age","name");
return $arr;
}
function __wakeup(){ //指定反串行化時(shí),提取出來(lái)的值
$this -> sex = "woman";
}
}
2. 串行化代碼
require("./Person.class.php");
$p = new Person(21,"du","man"); //定義Person類(lèi)對(duì)象
$pString = serialize($p); //對(duì)對(duì)象進(jìn)行串行化
file_put_contents("./file.txt",$pString);//存到文件里
3. 反串行化代碼
require("./Person.class.php");//反串行化時(shí),也要包含原類(lèi)
$pString = file_get_contents("./file.txt");//從文件中取出串行化的值
$p = unserialize($pString);//進(jìn)行反串行化
【PHP中串行化用法】相關(guān)文章:
php中引用的用法分析06-22
php中rename函數(shù)用法08-08
PHP中l(wèi)ist方法用法示例04-14
PHP中for循環(huán)語(yǔ)句的幾種“變態(tài)”用法04-10
PHP中redis的用法深入分析04-28
PHP中final關(guān)鍵字用法08-14