本文實例講述了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相關內容感興趣的讀者可查看本站專題:《php面向對象程序設計入門教程》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《PHP網絡編程技巧總結》、《PHP數組(Array)操作技巧大全》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。