What is the function of the __wakeup magic method in php?

Asked

Viewed 337 times

2

I read the documentation, but it wasn’t very clear. __wakeup() reestablishes connection to the database?

For example, I have a script that runs for quite a while, there comes a time when the connection to the database that was opened is lost. If I put it on __wakeup() the method that establishes the connection, it will be redone? If not, how can I do this? Remembering that everything, transactions, connection to DB and etc; are within the same class.

1 answer

3


With magical method __wakeup() you can rebuild serialized objects through the method unserialize(). Object serialization is useful when you need to transport objects to be executed elsewhere (in queues (queues) running on another server for example) or need to store the state of an object in a string.

Remembering that this magical method is in disuse in favor of the interface Serializable present since PHP 5.1.

See an example of how to implement the interface Serializable:

<?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, enough an hour the connection to the bank that was opened is lost. If I put on the __wakeup() the method that establishes the connection, it will be redo? If not, how can I do it? Remembering that everything, transactions, connection to DB and etc; are within the same class.

These magical method doesn’t work that way. In this case you can capture some kind of Exception and give a Retry connection without having to serialize an object for example. You will probably lose information from transactions in that case.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.