PHP串行化與反串行化實例分析
本文實例講述了PHP串行化與反串行化。分享給大家供大家參考,具體如下:
對象也是一種在內(nèi)存中存儲的數(shù)據(jù)類型,他的壽命通常隨著生成該對象的程序的終止而終止。有時候可能需要把對象的狀態(tài)保存下來,需要時再將其回復(fù)。串行化是把每個對象轉(zhuǎn)化為二進制字符串。
<?php
class Person {
var $name;
var $sex;
var $age;
function __construct($name = "", $sex = "男", $age = 22) {
$this->name = $name;
$this->sex = $sex;
$this->age = $age;
}
function say() {
echo $this->name . "在說話<br/>";
}
function run() {
echo "在走路·<br/>";
}
//串行化的時候自動調(diào)用,成員$sex被忽略,只串行$name,$age
function __sleep() {
$arr = array("name","age");
return $arr;
}
//反串行化時自動調(diào)用
function __wakeup() {
$this->age = 33;
}
}
class Student extends Person {
var $school;
function __construct($name = "", $sex = "男", $age = 22,$school="") {
parent::__construct($name,$sex,$age);
$this->school = $school;
}
function study() {
echo $this->name."正在".$this->school."學習<br/>";
}
}
class Teacher extends Student {
var $wage;
function teaching() {
echo $this->name."正在".$this->school."教學,每月工資為".$this->wage."<br/>";
}
//如果調(diào)用了不存在的方法,將會自動調(diào)用__call(),不會報錯
function __call($functionName,$args) {
echo "函數(shù)名:".$functionName;
print_r($args);
echo "<br/>";
}
}
$teacher1 = new Teacher("kaifu","男",22);
$teacher1->school = "edu";
$teacher1->wage = 4000;
$teacher1->say();
$teacher1->study();
$teacher1->teaching();
$teacher1->hello(1,2,3);
?>
<?php
require_once 'Person.php';
$teacher = new Teacher("tom","男",22);
$teacher_str = serialize($teacher);
file_put_contents("file.txt", $teacher_str);
//反串行化
$objStr = file_get_contents("file.txt");
$t = unserialize($objStr);
echo $t->age;
?>
串行化 file.txt :
O:7:"Teacher":2:{s:4:"name";s:3:"tom";s:3:"age";i:22;}

更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
- PHP中串行化用法示例
- 詳解PHP對象的串行化與反串行化
- php面向?qū)ο笕ヂ?(十六) 對象的串行化
- PHP中的串行化變量和序列化對象
- PHP面向?qū)ο蟪绦蛟O(shè)計方法實例詳解
- PHP面向?qū)ο罄^承用法詳解(優(yōu)化與減少代碼重復(fù))
- PHP面向?qū)ο蟪绦蛟O(shè)計高級特性詳解(接口,繼承,抽象類,析構(gòu),克隆等)
- PHP面向?qū)ο蟪绦蛟O(shè)計之命名空間與自動加載類詳解
- PHP面向?qū)ο蟪绦蛟O(shè)計之對象生成方法詳解
- PHP面向?qū)ο蟪绦蛟O(shè)計組合模式與裝飾模式詳解
- PHP入門教程之面向?qū)ο蟮奶匦苑治?繼承,多態(tài),接口,抽象類,抽象方法等)
相關(guān)文章
PHP Class&Object -- 解析PHP實現(xiàn)二叉樹
本篇文章是對PHP中二叉樹的實現(xiàn)代碼進行詳細的分析介紹,需要的朋友參考下2013-06-06
PHP將Excel導(dǎo)入數(shù)據(jù)庫及數(shù)據(jù)庫數(shù)據(jù)導(dǎo)出至Excel的方法
這篇文章主要介紹了PHP將Excel導(dǎo)入數(shù)據(jù)庫及數(shù)據(jù)庫數(shù)據(jù)導(dǎo)出至Excel的方法,涉及php操作數(shù)據(jù)庫及Excel的相關(guān)技巧,需要的朋友可以參考下2015-06-06
PHP基于cookie與session統(tǒng)計網(wǎng)站訪問量并輸出顯示的方法
這篇文章主要介紹了PHP基于cookie與session統(tǒng)計網(wǎng)站訪問量并輸出顯示的方法,涉及PHP基于cookie與session讀寫操作記錄網(wǎng)站訪問量及調(diào)用圖片形式輸出對應(yīng)數(shù)量的實現(xiàn)技巧,需要的朋友可以參考下2016-01-01

