©
Dokumen ini menggunakan Manual laman web PHP Cina Lepaskan
所有php里面的值都可以使用函数 serialize() 来返回一个包含字节流的字符串来表示。 unserialize() 函数能够重新把字符串变回php原来的值。 序列化一个对象将会保存对象的所有变量,但是不会保存对象的方法,只会保存类的名字。
为了能够 unserialize() 一个对象,这个对象的类必须已经定义过。如果序列化类A的一个对象,将会返回一个跟类A相关,而且包含了对象所有变量值的字符串。 如果要想在另外一个文件中解序列化一个对象,这个对象的类必须在解序列化之前定义,可以通过包含一个定义该类的文件或使用函数 spl_autoload_register() 来实现。
<?php
// classa.inc:
class A {
public $one = 1 ;
public function show_one () {
echo $this -> one ;
}
}
// page1.php:
include( "classa.inc" );
$a = new A ;
$s = serialize ( $a );
// 把变量$s保存起来以便文件page2.php能够读到
file_put_contents ( 'store' , $s );
// page2.php:
// 要正确了解序列化,必须包含下面一个文件
include( "classa.inc" );
$s = file_get_contents ( 'store' );
$a = unserialize ( $s );
// 现在可以使用对象$a里面的函数 show_one()
$a -> show_one ();
?>
当一个应用程序使用函数 session_register() 来保存对象到会话中时,在每个页面结束的时候这些对象都会自动序列化,而在每个页面开始的时候又自动解序列化。 所以一旦对象被保存在会话中,整个应用程序的页面都能使用这些对象。但是, session_register() 这个函数在php5.3.0已经废弃,而且在php6.0.0就不再支持,所以不要依赖这个函数。
在应用程序中序列化对象以便在之后使用,强烈推荐在整个应用程序都包含对象的类的定义。 不然有可能出现在解序列化对象的时候,没有找到该对象的类的定义,从而把没有方法的类__PHP_Incomplete_Class_Name作为该对象的类,导致返回一个没有用的对象。
所以在上面的例子中,当运行session_register("a"),把变量 $a 放在会话里之后,需要在每个页面都包含文件classa.inc,而不是只有文件page1.php和page2.php。
[#1] Harshwardhan (iamsmart9900 at gmail dot com) [2015-10-25 14:30:11]
class UnSerializer {
public function __construct($filename_with_path) {
$this->filename = $filename_with_path;
if ($this->filename == true) {
return true;
} else {
echo 'File Name Error';
}
}
public function check_file_validity() {
$this->validity = file_exists($this->filename);
if ($this->validity == true) {
return true;
} else {
echo 'File Not Found !';
}
}
public function getting_file_content() {
if ($this->validity == true) {
$this->content = file_get_contents($this->filename);
if ($this->content == true) {
return true;
} else {
echo 'We Can\'t Reach to the Data';
}
} else {
echo 'File Not Found !';
}
}
public function get_unserial_data() {
$this->check_file_validity();
$this->getting_file_content();
if (!is_null($this->content)) {
$this->unserializedval = unserialize($this->content);
if ($this->unserializedval == true) {
return true;
}
} else {
echo 'We Can\'t Reach to the Data';
}
}
public function get_unserialized_value() {
return $this->unserializedval;
}
}
$object = new UnSerializer('example_directory/filename');
$object->get_unserial_data();
var_dump($object->get_unserialized_value());
[#2] mjdragonexpert23 at gmail dot com [2015-04-01 04:39:03]
It is important to note that you cannot use the following characters in any array that gets serialized or deserializing will fail: single quote, double quote, colon, or semicolon. To get around this, use the base64_encode function after using serialize when you save the data. When you need to unserialize use the base64_decode function first then unserialize.
[#3] michael at smith-li dot com [2015-02-23 19:28:34]
Reading this page you'd be left with the impression that a class's `serialize` and `unserialize` methods are unrelated to the `serialize` and `unserialize` core functions; that only `__sleep` and `__unsleep` allow you to customize an object's serialization interface. But look at http://php.net/manual/en/class.serializable.php and you'll see that there is a more straightforward way to control how a user-defined object is serialized and unserialized.
[#4] wbcarts at juno dot com [2009-12-20 12:39:21]
PHP OBJECT SERIALIZATION
I use a database to store info rather than storing PHP Objects themselves. However, I find that having a PHP Object acting as an interface to my db is way useful. For example, suppose I have a TABLE called 'user' that looks like this.
CREATE TABLE user {
user_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
user_first VARCHAR(24) NOT NULL,
user_last VARCHAR(24) NOT NULL,
PRIMARY KEY (user_id)
);
Then I would create a PHP Class definition like so:
<?php
require('includes/db_connect.php');
class User
{
protected $user_id;
protected $user_first;
protected $user_last;
public function __construct($id, $first, $last)
{
$this->user_id = $id;
$this->user_first = $first;
$this->user_last = $last;
}
# FUNCTIONS TO RETRIEVE INFO - DESERIALIZE.
public static function db_user_by_id($dbc, $id)
{
$query = "SELECT * FROM user WHERE user_id=$id LIMIT 1";
return User::db_select($dbc, $query);
}
public static function db_user_by_name($dbc, $first, $last)
{
$query = "SELECT * FROM user WHERE user_first='$first' AND user_last='$last' LIMIT 1";
return User::db_select($dbc, $query);
}
protected static function db_select($dbc, $query);
{
$result = mysqli_query($dbc, $query);
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_array($result, MYSQLI_NUM);
return new User($row[0], $row[1], $row[2]);
}
}
# FUNCTIONS TO SAVE INFO - SERIALIZE.
public function insert($dbc)
{
$query = "INSERT INTO user VALUES (NULL, '$this->user_first', '$this->user_last')";
$result = mysqli_query($dbc, $query);
}
public function update($dbc)
{
$query = "UPDATE user SET user_first='$this->user_first', user_last='$this->user_last' WHERE user_id=$this->id LIMIT 1";
$result = mysqli_query($dbc, $query);
}
# GETTER and SETTER FUNCTIONS - DO NOT ALLOW SETTING OF ID
public function getId() {return $this->user_id;)
public function getFirst() {return $this->user_first;)
public function getLast() {return $this->user_last;)
public function setFirst($first) {$this->user_first = $first;}
public function setLast($last) {$this->user_last = $last;}
# CUSTOM FUNCTIONS
public function getFullName() {return $this->user_first . ' ' . $this->user_last;}
public function getLastFirst() {return $this->user_last . ', ' . $this->user_first;}
}
?>
Using PHP Objects for SERIALIZATION and DESERIALIZATION is now super-easy, for example:
<?php
require('User.php');
// INSERT a new user.
$user = new User(0, 'Frank', 'American');
$user->insert($dbc); // done!
// UPDATE an existing user.
$user = User::db_user_by_id($dbc, 223);
$user->setFirst('Johnny');
$user->update($dbc); // done!
mysqli_close($dbc);
?>
[#5] php at lanar dot com dot au [2009-10-18 16:47:58]
Note that static members of an object are not serialized.