這篇文章主要介紹了PHP串列化與反串列化,結合實例形式分析了php物件導向程式設計及serialize與unserialize函數進行串列化、反串列化相關使用技巧,需要的朋友可以參考下
本文實例講述了PHP串行化與反串行化。分享給大家供大家參考,具體如下:
物件也是一種在記憶體中儲存的資料類型,他的壽命通常隨著產生該物件的程式的終止而終止。有時候可能需要把物件的狀態保存下來,需要時再回覆。串行化是把每個物件轉換為二進位字串。
<?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/>"; } //串行化的时候自动调用,成员$sex被忽略,只串行$name,$age function __sleep() { $arr = array("name","age"); return $arr; } //反串行化时自动调用 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/>"; } //如果调用了不存在的方法,将会自动调用__call(),不会报错 function __call($functionName,$args) { echo "函数名:".$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;}
以上就是本文的全部內容,希望對大家的學習有幫助。
相關推薦:
PHP物件導向-物件序列化serialize(),__sleep(),__wakeup () 的程式碼詳解
##PHP中串列化的使用
以上是PHP串行化與反串行化實例分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!