魔术函数 __sleep__wakeup

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

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

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

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

add a note

User Contributed Notes 3 notes

up
9
Ninsuo
1 year ago
If you want to serialize all but one properties, you can use:

<?php

class A
{

   protected
$a = 1;
   protected
$b = 2;
   protected
$c = 3;
   protected
$d = 4; // unwanted

   
public function __sleep()
    {
        return
array_diff(array_keys(get_object_vars($this)), array('d'));
    }
   
}
up
-11
Ninsuo
1 year ago
If you want to serialize all but one properties, you can use:

<?php

class MyClass
{
   protected
$a;
   protected
$b;
   protected
$c;
   protected
$d; // unwanted

   
public function __sleep()
    {
        return
array_diff(get_object_vars($this), array('d'));
    }

}
up
-41
ranware2200 at yahoo dot com
5 years ago
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();
?>