__construct (), __DESTURCT (), __call (), __callstatic (), __get (), __set (), __isset (), __unset (), __sleep (), __wakeup (), __ ToString (), __invoke (), __set_state (), __clone (), and, __debuginfo () are known in PHP as " Magic Methods" (Magic methods). You cannot use these method names when naming your own class methods.
Note: __sleep () cannot return the name of the private member of the parent class. Doing so produces a E_NOTICE
level of error. Can be replaced with Serializable interface.
The __sleep () method is commonly used to commit uncommitted data, or similar cleanup operations. At the same time, if there are some very large objects, but do not need to save all, this function is very useful.
In contrast,unserlalize () checks for the existence of a __wakeup () method. If present, the __wakeup method is called before the resource required by the object is prepared beforehand.
__wakeup () is often used in deserialization operations, such as re-establishing a database connection, or performing other initialization operations.
Example: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 ();
}
}
?>
PHP Magic Method