Magic Methods in PHP
In this article I explain PHP magic methods like sleep method and wakeup methods.
In this article you will be learn the PHP "magic" methods. The PHP magic methods start with double underscore characters, as in "_" and another "_" (in other words "_ _"), and they are:
Why they are called "magic" methods
Its definition is provided by programmers, in other words by you. PHP does not provide the definition of these methods. The programmer writes the code that defines what actually these methods will do. The user cannot call these methods, that is why it is called "magic" methods because PHP will call the functions behind the scene and these methods are always defined within the class. I am providing an example to clarify my point better.
_sleep and _wakeup method in PHP
It is useful when we have a large object in our program and we do not want to save the object completely. It is also used to commit and perform simple clean up tasks.
It is useful when we want to reconstruct any resource that the object may have, or say it is used to reestablish the database connections that may have been lost.
Example of __sleep and __wakeup magic methods
private $serverName, $userName,$password,$dbname;
public function __construct($serverName, $userName,$password,$dbName)
private function connect()
die('Could not connect: ' . mysql_error());
echo "Connection is Successfully established.";
public function __sleep()
return array($serverName, $userName,$password,$dbName);
public function _wakeup()