What’s the special meaning of __sleep and __wakeup?
Posted by Raj
What’s the special meaning of __sleep and __wakeup?
__sleep returns the array of all the variables than need to be saved.
__wakeup retrieves them.
__sleep() and __wakeup() run prior to serialize() and unserialize() respectively.
Example:
<?php
class DBConn
{
protected $conn;
private $host, $username, $password, $db;
public function __construct($host, $username, $password, $db)
{
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->connect();
}
private function connect()
{
$this->conn = mysql_connect($this->host, $this->username, $this->password);
mysql_select_db($this->db, $this->conn);
}
public function __sleep()
{
return array('host', 'username', 'password', 'db');
}
public function __wakeup()
{
$this->connect();
}
}
?>
This entry was posted on October 4, 2009 at 12:14 pm, and is filed under
__sleep,
__sleep and __wakeup,
__sleep and __wakeup in PHP,
OOP interview questions and answers,
PHP,
PHP interview questions and answers,
php5 magic methods,
Question
.You can leave a response, or trackback from your own site.