本文實例講述了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(){ //指定串行化時能提取的成員屬性,沒有參數(shù),但是必須返回一個數(shù)組 $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); //對對象進(jìn)行串行化 file_put_contents("./file.txt",$pString);//存到文件里3. 反串行化代碼
<?php require("./Person.class.php");//反串行化時,也要包含原類 $pString = file_get_contents("./file.txt");//從文件中取出串行化的值 $p = unserialize($pString);//進(jìn)行反串行化 var_dump($p); //這個 $p就是之前那個串行化的對象,一樣用,但是里面的值被我改了希望本文所述對大家PHP程序設(shè)計有所幫助。
新聞熱點
疑難解答
圖片精選