Home Tutorial Php Phpoop PHP Sleep Wakeup Method

 
 

Share on Google+Share on Google+
PHP Sleep Wakeup Method
Posted on: March 4, 2010 at 12:00 AM
Advertisement
This is one of the magic method provided by PHP. The __sleep function in PHP is useful when we have very large objects in our program and we do not want to save the object completely and __wakeup() of PHP is used to reestablish the database connections that may have been lost during any phenomenon.

The __sleep and __wakeup Function in PHP

The __sleep function in PHP is useful when we have very large objects in our program and we do not want to save the object completely, this method is useful for commit pending or for purging purpose.

The serialize method checks every program whether it has a magic method __sleep or not. If so, then the function execute that method prior to any other function moreover it can clean up the object and will return an array which contains the name of each variable.

On the other hand __wakeup is used to reestablish the database connections that may have been lost during any phenomenon like serialization or reinitialization tasks. unserialize() method checks the presence of __wakeup() function in a program, if so then it reconstruct any resources that the object may have.

PHP Sleep and Wakeup Method Example:

<?php

class DBConnection{

private $host, $user, $password,$link,$db;

public function __construct($host, $user, $password,$db)

{

$this->host=$host;

$this->user=$user;

$this->password=$password;

$this->db=$db;

$this->connect();

}

private function connect()

{

$this->link=mysql_connect($this->host,$this->user,$this->password);

mysql_select_db($this->db,$this->link);

if(! $this->link)die("Could not connect").mysql_error();

else echo"Connected<br/>";

}

function __sleep()

{

return array($host,$user,$password,$db);

}

function __wakeup()

{

$this->connect();

}

}

$var=new DBConnection("localhost","root","","ajax");

$var->__wakeup();

?>

Output:

Connected
Connected

Advertisement

Related Tags for PHP Sleep Wakeup Method:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: March 4, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com