Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Magic Methods

The function names __construct, __destruct, __call, __callStatic, __get, __set, __isset, __unset,
__sleep, __wakeup, __toString, __invoke, __set_state and __clone are magical in PHP classes.
You cannot have functions with these names in any of your classes unless you want the magic
functionality associated with them.

Caution

PHP reserves all function names starting with __ as magical. It is recommended that you do not
use function names with __ in PHP unless you want some documented magic functionality.

__sleep and __wakeup

serialize() checks if your class has a function with the magic name __sleep. If so, that function is
executed 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.

Note:

It is not possible for __sleep to return names of private properties in parent classes. Doing this
will result in an E_NOTICE level error. Instead you may use the Serializable interface.

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 do not need to 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 the 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.

Example #1 Sleep and wakeup

<?php
class Connection
{
    protected $link;
    private $server, $username, $password, $db;
    
    public function __construct($server, $username, $password, $db)
    {
        $this->server = $server;
        $this->username = $username;
        $this->password = $password;
        $this->db = $db;
        $this->connect();
    }
    
    private function connect()
    {
        $this->link = mysql_connect($this->server, $this->username, $this-
>password);
        mysql_select_db($this->db, $this->link);
    }
    
    public function __sleep()
    {
        return array('server', 'username', 'password', 'db');
    }
    
    public function __wakeup()
    {
        $this->connect();
    }
}
?>

You might also like