1

According to the documentation :

unserialize() checks for the presence of a function with the magic name __wakeup(). If present, this function can reconstruct any resources that the object may have.

The intended use of __wakeup() is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.

If my object has not defined __wakeup() method I can still have reconstructed form of my object using unserialize() then why this magic method is there in PHP?

Documentation is also saying the same thing that __wakeup() function can reconstruct any resources that the object may have just like unserialize() do.

When this magic method __wakeup() gets called before unserialization starts or after unserialization finished?

  • 1
    `__wakeup()` is execute after unserialization but before returning the object. You can interact with the full object with this method eg `public function __wakeup(){var_dump($this);}` – Scuzzy Dec 08 '17 at 04:22

1 Answers1

1

Maybe this code can help you, when you serialize one object instance of Test the database connection is closed and is not saved in serialized form, when you unserialize this object the __wakeup() method reestablish the database connection upon unserialization, so you can use these resources inmediatly, you can see the use of $objTest->getUserInfo() upon unserialization. You can use __wakeup to do calculus or open files connections, etc...

class Test
{
    public $userId;

    private $_db = null;

    public function __wakeup()
    {
        if (null === $this->_db)
        {
            $this->_db = getConnection();
        }
    }

    public function getUserInfo(){
        $info = $this->_db->query("SELECT * FROM users WHERE id = " . intval($this->userId, 10));
        return $info;
    }
}

function getConnection(){
    $user = "my_user_db";
    $password = "my_password_db";
    return new PDO('mysql:host=my_host_db;dbname=my_database', $user, $password);
}

$objTest = unserialize("O:4:\"Test\":2:{s:6:\"userId\";s:2:\"43\";s:9:\" Test _db\";N;}", ['Test']);
$userInfo = $objTest->getUserInfo();
Mauricio Florez
  • 1,112
  • 8
  • 14