Team LiB
Previous Section Next Section

Object Serialization

Earlier in the book, I introduced the concept of serializing complex data structures such as arrays into a string that could then be stored and restored at a later time using the serialize() and unserialize() functions. This concept applies to objects as well; however, because of the nature of objects, added functionality is provided. When serializing an object, PHP gives it the opportunity to perform any clean up necessary and, if desired, provide a specific list of properties that should be stored. When the object is then later restored using the unserialize() function, PHP again provides an opportunity to the object to recreate any properties that were not saved and initialize itself again.

These two tasks are all accomplished using two special methods: __sleep() and __wakeup(). These methods accept no parameters, but unlike most callback methods we've discussed, PHP does expect the __sleep() function to return an indexed array. This array should be an indexed array of strings representing the properties that should be included within the serialization. Any properties that are not provided in this list will not be saved in the serialization. When the object is restored using the unserialize() function, the __wakeup() method is then called, allowing the object to, if necessary, reinitialize itself and re-create those properties that were omitted during serialization. To demonstrate these methods in action, consider Listing 13.24:

Listing 13.24. Using __sleep() and __wakeup() for Objects
     class UserClass {
          public $sessionID;
          public $username;

          public function __sleep() {
               /* Destroy the session */
               return array("username");
          public function __wakeup() {
               /* Restore the session */
               $this->sessionId = session_id();
     $user = new UserClass;
     $user->sessionId = session_id();
     $seralized_user = serialize($user);

     /* Simulate losing the $user variable */
     $user = unserialize($serialized_user);

Listing 13.24 provides an example of when it might be desirable to omit certain properties of a class when serializing it into a string. In this case, where the class contains the session ID for the current session, it is likely that when the class is restored, the session will become invalid. Thus, the __sleep() function saves information that is relevant and re-creates a new value for the $sessionId property when the class is restored via the __wakeup() function. This technique can be applied with many things, including database connection resources.

    Team LiB
    Previous Section Next Section