The __wakeup() magic method is mainly responsible of customizing the deserialization or unserialization of a class.
We’ve already learnt on how the __sleep()
magic method works & how can we serialize and unserialize class in PHP.
The __wakeup()
magic method is directly related to __sleep()
magic method & its useful in customizing the unserialization of data collection inside of the class.
Simple Example
Let’s look out a simple example on how __wakeup()
magic method works, its opposite to __sleep()
magic method.
class DevPeel
{
public $name = 'devpeel';
public function __sleep(){
return ['name'];
}
public function __wakeup(){
var_dump('woken up');
}
}
$class = new DevPeel();
$string = serialize($class);
$class = unserialize($string);
If you run this script, you’ll notice that __wakeup()
magic method only runs when we unserialize on the serialized string.