There are many magic methods in PHP like
__construct(), __destruct(), __callback(), __get(), __set(), __sleep(), __wake() and many more. But we will be takingon on __sleep() and __wake().
__sleep(): serialize() checks if your class has a function with the magic name __sleep(). If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.
__construct(), __destruct(), __callback(), __get(), __set(), __sleep(), __wake() and many more. But we will be takingon on __sleep() and __wake().
__sleep(): serialize() checks if your class has a function with the magic name __sleep(). If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.
- serialize() is used for the representation of the storage class for storing the value.Serializing an object means converting it to a byte stream representation that can be stored in a file.
The use of __sleep() to commit the pending task. If a bulk data is being inserted then at that time __sleep can be used. it will not release the object unless the work is not completed. Or if a table is being altered and updated in MySQL then also it can be used.
__wakeup():unserialize the opposite of serialize. And __wakeup() is used to reestablish the connection if it is lost during the serialization task.
eg-
<?php
class Connection
{
protected $link;
private $dsn, $username, $password;
public function __construct($dsn, $username, $password)
{
$this->dsn = $dsn;
$this->username = $username;
$this->password = $password;
$this->connect();
}
private function connect()
{
$this->link = new PDO($this->dsn, $this->username, $this->password);
}
public function __sleep()
{
return array('dsn', 'username', 'password');
}
public function __wakeup()
{
$this->connect();
}
}?>
Comments
Post a Comment