PHP 5.4.31 Released

对象序列化

序列化对象 - 在会话中存放对象

所有php里面的值都可以使用函数serialize()来返回一个包含字节流的字符串来表示。unserialize()函数能够重新把字符串变回php原来的值。 序列化一个对象将会保存对象的所有变量,但是不会保存对象的方法,只会保存类的名字。

为了能够unserialize()一个对象,这个对象的类必须已经定义过。如果序列化类A的一个对象,将会返回一个跟类A相关,而且包含了对象所有变量值的字符串。 如果要想在另外一个文件中解序列化一个对象,这个对象的类必须在解序列化之前定义,可以通过包含一个定义该类的文件或使用函数spl_autoload_register()来实现。

<?php
// classa.inc:
  
  
class {
      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.phppage2.php

add a note add a note

User Contributed Notes 3 notes

up
38
php at lanar dot com dot au
4 years ago
Note that static members of an object are not serialized.
up
0
me at iabdullah dot info
1 day ago
In case you're reading the official book that written by Rasmus and the other authors, Here is the serialization and unserialization Example (6-3) since it is written in the old fashion way (using session_register() ..) and has some typos.

(Log.php)
an object class, Log, provides two useful methods: write() to append a message to the logfile, and read() to fetch the current contents of the logfile. It uses __wakeup() to reopen the logfile and __sleep() to close the logfile.

<?php
class Log {
    private
$filename;
    private
$fh;

    public function
__construct ($fn)
    {
       
$this->filename = $fn;
       
$this->open();
    }

    public function
open ()
    {
       
$this->fh = fopen ($this->filename,'a') or die ("Can't open {$this->filename} !");
    }
    public function
write ($note)
    {
       
fwrite($this->fh, "{$note}\n");
    }
    public function
read ()
    {
        return
join ('', file($this->filename));
    }
    public function
__wakeup()
    {
       
$this->open();
    }
    public function
__sleep ()
    {
       
fclose ($this->fh);
        return array(
"filename");
    }
}
?>
Store the Log class definition in a file called Log.inc.

(front.php)
The front.php uses the Log class and PHP sessions to create a persistent log variable, $Logger.
<?php
include_once ("Serialization.php");
session_start();
?>
<html>
<head>
<title>Front Page</title>
</head>
<body>
<?php
$now
= strftime("%c");   

if (!isset(
$_SESSION['Logger']))
{
   
$l = new Log ("tmp/persistent_log");
   
$_SESSION['Logger'] = $l;
   
$l->write("Created {$now}");

    echo (
"<p> Created Session and Persistent Log File </p>");
}
else
{
   
$_SESSION['Logger']->write("Viewed Page 1 at {$now}");
    echo
"<p> The Log content : </p>";
    echo
nl2br($_SESSION['Logger']->read());
}
?>
<a href="next.php"> Move the next Page !!</a>
</body>
</html>

(next.php)
The file next.php shows , an HTML page, Following the link from the front page to this page triggers the loading of the persistent object $logger. The __wakeup() call reopens the logfile so the object is ready to be used.
<?php
include_once ("Serialization.php");
session_start();
?>
<html>
<head>
<title>Next Page</title>
</head>
<body>
<?php
$now
= strftime("%c");   
$logger = $_SESSION['Logger'];

$logger->write("Viewed Page 2 at {$now}");
echo
"<p> The Log content : </p>";
echo
nl2br($logger->read());
?>
</body>
</html>

Create folder 'tmp' and file 'persistent_log' to avoid getting fopen warning error message.
up
-23
wbcarts at juno dot com
4 years ago
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);

?>
To Top