令人兴奋的是,PHP也支持这一特性,而且从PHP3就开始支持了,它是通过Serialize()和Unserialize()这两个函数来实现的。其实,像ASP这样的开发环境也隐式支持这一特性——在Session或Application对象中保存应用程序对象就是一种持久化的表现,但遗憾的是,ASP并没有显式提供这一接口。
在PHP中,几乎任何类型(这包括Integer、Boolean、Float、Array和Object)的变量都可以被序列化。之所以说“几乎”,是因为唯独Resource类型不支持序列化,这完全是因为PHP中的Resource类型其实是指针的缘故。至于String类型,由于它本身就是字节流,所以根本没有序列化的必要。
下面将介绍Serialize()和Unserialize()两个函数的用法:
string serialize (mixed value):返回value被序列化后的字节流;
mixed unserialize (string str):返回将str进行装配后的对象。
下面是这两个函数的应用实例:
//class.inc.php文件,用于保存类的信息
//用于测试的用户信息类
class Userinfo
{
var $username;
var $password;
var $datetime;
function Userinfo($username, $password, $datatime)
{
$this -> username = $username;
$this -> password = $password;
$this -> datetime = $datetime;
}
function output()
{
echo "User Information ->
";
echo "Username: ".$this -> username."
";
echo "Password: ".$this -> username."
";
echo "Datetime: ".$this -> username."
";
}
}
?>
//login.php文件,用于注册新用户
//导入类文件
require_once("class.inc.php");
//新建对象
$user = new Userinfo($_POST['username'], $_POST['password'], date("Y-n-j H:i:s"));
//序列化对象
$user = Serialize($user);
//将对象写入本地数据库
$con = mysql_connect();
mysql_select_db("test");
mysql_query($con, "INSERT INTO testTable (id, userinfo) VALUES ('1', '$user')");
mysql_close($con);
?>
//userinfo.php文件,用于显示用户信息
require_once("class.inc.php");
//从数据库中取出对象
$con = mysql_connect();
mysql_select_db("test");
$result = mysql_query($con, "SELECT * FROM testTable WHERE id=1");
$record = mysql_fetch_assoc($result);
$user = Unserialize($record['userinfo']);
//输出用户信息
$user -> output();
mysql_free($result);
mysql_close($con);
?>
在对象序列化中,最重要的是在“装配”的页面中一定要包含该对象的类的定义信息,否则会出现错误。当然,上里只是用于测试,在实际的应用中,为了防止序列化后的对象的内容被更改,一般还要对字节流进行“数字签名”,在装配时,再对“签名”进行验证,以防止对象信息被非法篡改。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor