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.

add a note add a note

User Contributed Notes 2 notes

up
21
Ninsuo
9 years 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
-25
Ninsuo
9 years 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'));
    }

}
To Top