PHP Sleep Wakeup Method


 

PHP Sleep Wakeup Method

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.

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

0

}

}

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

1

$var->__wakeup();

?>

Output:

2

Connected
Connected

Ads