Thanks in advance
__sleep & __wakeup
Moderator: General Moderators
- mudkicker
- Forum Contributor
- Posts: 479
- Joined: Wed Jul 09, 2003 6:11 pm
- Location: Istanbul, TR
- Contact:
__sleep & __wakeup
Yesterday when I was surfing in the manual, I read about the new magical functions of OOP in PHP 5
__sleep & __wakeup . But I didn't really understand their function. Is there anyone who can tell me clearly how they work?
Thanks in advance
Thanks in advance
simplified:
for example if you have a class with a connection to a database.
everytime this class is stored in a session, it might be nice to close the connection with the database.
and everytime it is retrieved from a session it might be nice to open the connection again.
in this case __sleep and _wakeup seem appropriate.
Code: Select all
function serialize($what)
{
if (is_object($what) && method_exists($what, '__sleep')
{
$what->__sleep();
}
// do other stuff for serialzing
}
function unserialize($what)
{
if (is_object($what) && method_exists($what, '__wakeup')
{
$what->__wakeup();
}
// do other stuff for unserializing
}for example if you have a class with a connection to a database.
everytime this class is stored in a session, it might be nice to close the connection with the database.
and everytime it is retrieved from a session it might be nice to open the connection again.
in this case __sleep and _wakeup seem appropriate.
Code: Select all
class What
{
private $db;
function __construct()
{
$this->db = $this->connect();
}
function __sleep()
{
$this->db = close();
}
function __wakeup()
{
$this->db = connect();
}
function connect()
{
$this->db = mysql_connect('host', 'user', 'pass');
mysql_select_db('database', $this->db);
return $this->db;
}
function disconnect()
{
mysql_close($this->db);
}
}