Using __wakeup()
The topic of serializable objects would not be complete without the serialize()
method counterpart--the unserialize()
method. If the serialize()
method call triggers the object's __sleep()
magic method, it is logical to expect there is a similar behavior for deserialization. Rightfully so, calling the unserialize()
method upon a given object triggers its __wakeup()
magic method.
The intended use of __wakeup()
is to reestablish any resources that might have been lost during serialization and perform other reinitialization tasks.
Let's take a look at the following example:
<?php class Backup { protected $ftpClient; protected $ftpHost; protected $ftpUser; protected $ftpPass; public function __construct($host, $username, $password) { $this->ftpHost = $host; $this->ftpUser = $username; $this->ftpPass = $password; echo 'TEST!!!' . PHP_EOL; $this->connect(); } public function connect() { $this->ftpClient = ftp_connect...