Difference between __sleep and __wakeup in php
Posted by Raj
Difference between __sleep and __wakeup in php
__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();
}
$c=new DBConn("localhost","root","","testdb");
$c->__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();
}
$c=new DBConn("localhost","root","","testdb");
$c->__wakeup();
}
?>
This entry was posted on October 4, 2009 at 12:14 pm, and is filed under
__sleep,
__sleep and __wakeup in PHP,
__wakeup,
Difference between __sleep and __wakeup in php,
PHP,
PHP interview questions and answers
.You can leave a response, or trackback from your own site.