Page 1 of 1

__sleep & __wakeup

Posted: Thu Oct 14, 2004 3:12 am
by mudkicker
Yesterday when I was surfing in the manual, I read about the new magical functions of OOP in PHP 5 :arrow: __sleep & __wakeup . But I didn't really understand their function. Is there anyone who can tell me clearly how they work?

Thanks in advance :wink:

Posted: Thu Oct 14, 2004 3:46 am
by timvw
simplified:

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);
        }

}

Posted: Thu Oct 14, 2004 3:59 am
by mudkicker
thank you for your post first.

hmm.. then it means kind a standby thing ? when we don't use tv we don't shut down only take it to standby.. this is the same idea i think.

btw, what does serialize-unserialize do ?

Posted: Thu Oct 14, 2004 4:13 am
by timvw
[php_man]serialize[/php_man]
[php_man]unserialize[/php_man]