PHP 5 Magic – __sleep() and __wakeup() methods
Hello Friends,
The magic method _sleep() and _wakeup() is called when an object is serialized. The magic method _sleep() and _wakeup() provides a method to clean up and restore objects before being serialized.
Working with _sleep()
_sleep() magic method is called when the object of a class is about to be serialized. This magic method _sleep() does not accept any parameter and returns an array. The array should contain a list of class members that should be serialized. This means that if you don’t wish to serialize a particular class member, you should not include it in the array. Look at the example below:
private $name;
private $credit_card_number;public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setCC($cc) {
$this->credit_card_number = $cc;
}
public function getCC() {
return $this->credit_card_number;
}
public function __sleep() {
return array(“name”); //because of this, only name is serialized
}
}
$c = new Customer();
$c->setName(“Timir”);
$c->setCC(“1234567890123456″);
$data = serialize($c).”\n”;
echo $data.”\n”;
Output:
O:8:â€Customerâ€:1:{s:14:†Customer nameâ€;s:5:â€Timirâ€;}
Working with the magic method __wakeup()
_wakeup() magic method is the opposite of the _sleep() method. It is called when the object of a class is about to be unserialized. This magic method _wakeup() does not accept any parameter nor returns anything. The _wakeup() method is responsible for setup operations after an object has been unserialized. Look at the example below:
private $name;
private $credit_card_number;
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setCC($cc) {
$this->credit_card_number = $cc;
}
public function getCC() {
return $this->credit_card_number;
}
public function __sleep() {
return array(“name”);
}
public function __wakeup() {
if($this->name == “Timir”) {
//you would ideally fetch CC data from Database
$this->credit_card_number = “1234567890123456″;
}
}
}
$c = new Customer();
$c->setName(“Timir”);
$c->setCC(“1234567890123456″);
$data = serialize($c).”\n”;
var_dump(unserialize($data));
Output:
object(Customer)#2 (2) {
[â€name:privateâ€]=>
string(5) “Timirâ€
[â€credit_card_number:privateâ€]=>
string(16) “1234567890123456″
}
Please leave comment or any question about this post.




