Use of PHP Magic Methods __sleep and __wakeup

空扰寡人 提交于 2019-11-29 23:41:35

As already described, __sleep() is called when you serialize() an object and __wakeup() after you unserialize() it.

Serialization is used to persist objects: You will get a representation of an object as a string that can then be stored in $_SESSION, a database, cookies or anywhere else you desire.

Resource values

However, serialize() cannot serialize (i.e. transform into a textual representation) value sof the resource type. This is why all of these values will go missing after unserialize()ing it.

Object graph

or members, and the member's members and the ... ad infinitum

Another, perhaps more important point is, that serialize() will traverse the entire object graph of $obj if you serialize it. This is great when you need it, but if you only need parts of the object and certain linked objects are "runtime-specific" and shared across a lot of objects but also by other objects, you may not want that behavior.

PHP handles cyclic graphs correctly! Meaning: If (a member of) $a links to $b, and $b links to $a is handled correctly however many levels deep.

Example - session specific (shared) objects

For instance, a $database object is referenced by $obj->db, but also by other objects. You will want $obj->db to be the same objects - after unserialize()ing - that all the other objects in your next session have, not an isolated instance of the database object.

In this case, you would have __sleep() method such as this:

/**
/* DB instance will be replaced with the one from the current session once unserialized()
 */
public function __sleep() {
    unset($this->db);
}

and then restore it like this:

public function __wakeup() {
    $this->db = <acquire this session's db object>
}

Another possibility is, that the object is part of some (global) datastructure where it needs to be registered. You could do this manually of course:

$obj = unserialize($serialized_obj);
Thing::register($obj);

However, if it is part of the objects contract that it needs to be in that registry, it's not a good idea to leave this magical call up to the user of your object. The ideal solution is, if the object cares about it's responsibilities, i.e. being registered in Thing. That's what __wakeup() allows you to do transparently (i.e. he need no longer worry about that magical dependency) to your client.

Similarly, you could use __sleep() to "un-register" an object if appropriate. (Objects are not destroyed when they're serialized, but it may make sense in your context.)

Closures

Last but not least, closures do not support serialization either. This means that you will have to re-create all attached closures in __wakeup().

Mohammed Asad

They are pretty much like hook functions, which we can use according to our needs. I came up with this simple real time example. Now try executing this code in two scenarios:

class demoSleepWakeup {
    public $resourceM;
    public $arrayM;

    public function __construct() {
        $this->resourceM = fopen("demo.txt", "w");
        $this->arrayM = array(1, 2, 3, 4); // Enter code here
    }

    public function __sleep() {
        return array('arrayM');
    }

    public function __wakeup() {
        $this->resourceM = fopen("demo.txt", "w");
    }
}

$obj = new demoSleepWakeup();
$serializedStr = serialize($obj);
var_dump($obj);
var_dump($serializedStr);
var_dump(unserialize($serializedStr));

Scenario 1:

First by commenting __sleep() and __wakeup() methods, check the output. You will find the resource missing when you unserialize it.

Scenario 2:

Now try running it uncommenting them, you will figure out that the object dumped in first and last var_dump would be same.

These methods are used when calling serialize() and unserialize() on the objects to make sure you have a hook to remove some properties like database connections and set them back when loading. This happens when storing objects in sessions among other things.

donald123

try out this

<?php
  $ob = new sleepWakeup();
  $safe_me = serialize($ob);
  $ob = unserialize($safe_me);
?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!