PHP串行化与反串行化基础概念
本案例详细解析了PHP语言中的串行化(Serialization)与反串行化(Unserialization)操作,旨在为读者提供实用的参考代码与说明。
对象作为内存中的一种数据类型,其生命周期通常依附于生成它的程序进程,一旦程序结束,对象便随之消失。但在某些场景下,我们需要将对象的当前状态持久化保存,以便后续恢复使用。实现这一目标的关键步骤是串行化,即把对象的结构和数据转换为一串二进制字符流。
<?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 . "在说话
";
}
function run() {
echo "在走路·
";
}
//串行化的时候自动调用,成员$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."学习
";
}
}
class Teacher extends Student {
var $wage;
function teaching() {
echo $this->name."正在".$this->school."教学,每月工资为".$this->wage."
";
}
//如果调用了不存在的方法,将会自动调用__call(),不会报错
function __call($functionName,$args) {
echo "函数名:".$functionName;
print_r($args);
echo "
";
}
}
$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程序设计的内容能为您提供有价值的参考与帮助。