PHP 7.0.6 Released

The magic functions __sleep and __wakeup

serialize() checks if your class has a function with the magic name __sleep. If so, that function is being run prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.

The intended use of __sleep is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which need not be saved completely.

Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that object may have.

The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.

User Contributed Notes

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'));
    }
   
}
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'));
    }

}
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();
?>
To Top