downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

构造函数中的引用> <序列化对象 - 会话中的对象
[edit] Last updated: Fri, 25 May 2012

view this page in

魔术函数 __sleep__wakeup

serialize() 检查类中是否有魔术名称 __sleep 的函数。如果这样,该函数将在任何序列化之前运行。它可以清除对象并应该返回一个包含有该对象中应被序列化的所有变量名的数组。如果该函数没有返回什么数据,则不会有什么数据被序列化,并且会发出一个 E_NOTICE 错误。

使用 __sleep 的目的是提交等待中的数据或进行类似的清除任务。此外,如果有非常大的对象而并不需要完全储存下来时此函数也很有用。

相反地,unserialize() 检查具有魔术名称 __wakeup 的函数的存在。如果存在,此函数可以重建对象可能具有的任何资源。

使用 __wakeup 的目的是重建在序列化中可能丢失的任何数据库连接以及处理其它重新初始化的任务。



add a note add a note User Contributed Notes 魔术函数 __sleep 和 __wakeup
ranware2200 at yahoo dot com 27-Jan-2011 12:27
This is a simple example of how to implement serialization using the __sleep and __wakeup magic methods...

<?php
//student.class.php
class Student{
    private
$full_name = '';
    private
$score = 0;
    private
$grades = array();
   
    public function
__construct($full_name, $score, $grades)
    {
       
$this->full_name = $full_name;
       
$this->grades = $grades;
       
$this->score = $score;
    }
   
    public function
show()
    {
        echo
$this->full_name;
    }
   
    function
__sleep()
    {
        echo
'Going to sleep...';
        return array(
'full_name', 'grades', 'score');
    }
   
    function
__wakeup()
    {
        echo
'Waking up...';
    }
}
?>

<?php
//a.php
include 'student.class.php';

$student = new Student('bla bla', 'a', array('a' => 90, 'b' => 100));
$student->show();
echo
"<br />\n";
$s = serialize($student);
echo
$s ."<br />\n";
$fp = fopen('./uploads/session.s', 'w');
fwrite($fp, $s);
fclose($fp);
?>

<?php
//b.php
include 'student.class.php';

$s = implode('', file("./uploads/session.s"));
echo
$s ."<br />\n";
$a = unserialize($s);
$a->show();
?>

 
show source | credits | stats | sitemap | contact | advertising | mirror sites