With magic method __wakeup()
you can rebuild serialized objects using the unserialize()
method. Object serialization is useful when you need to transport objects to be executed elsewhere (in queues running on another server for example) or need to store the state of an object in a string.
Remembering that this magic method is deprecated in favor of the Serializable
interface since PHP 5.1.
See an example of how to implement the Serializable
interface:
<?php
class obj implements Serializable {
private $data;
public function __construct() {
$this->data = "My private data";
}
public function serialize() {
return serialize($this->data);
}
public function unserialize($data) {
$this->data = unserialize($data);
}
public function getData() {
return $this->data;
}
}
$obj = new obj;
$ser = serialize($obj);
var_dump($ser);
$newobj = unserialize($ser);
var_dump($newobj->getData());
The return will be:
string (38) "C: 3:" obj ": 23: {s: 15:" My private data ";}"
string (15) "My private data"
Code extracted from documentation.
For example, I have a script that runs for a long time, arrives
one hour that the connection to the bank that was opened is lost. If I
__wakeup()
the method that establishes the connection, it will be
redone If not, how can I do this? Remembering everything, transactions, DB connection and etc; are within the same class.
These magical methods do not work that way. In this case you can capture some type of Exception
and give a retry on the connection without having to serialize an object for example. You will probably lose transactions information in this case.