The Sleep and Wakeup Magic Functions in PHP 5 - The sleep and wakeup methods in action (
Page 4 of 4 )
The best way to understand how the previously implemented "__sleep()" and "__wakeup()" magic methods do their business is by means of a concrete example that uses the "serialize()" and "unserialize()" PHP functions with an instance of the previous "User" class.
Based on this idea, below I created a simple script that performs this serialization/unserialization process in an approachable fashion. Look at it, please:
// example on using the 'User' class with the '__sleep()' and '__wakeup()' methods
$user = new User();
$user->fname = 'Alejandro';
$user->lname = 'Gervasio';
$user->email = 'alejandro@mydomain.com';
// display user data
echo 'First Name : ' . $user->fetch('fname') . ' Last Name : ' . $user->fetch('lname') . ' Email : ' . $user->fetch('email');
/*
displays the following
First Name : Alejandro Last Name : Gervasio Email : alejandro@mydomain.com
*/
// serialize user object
$user = serialize($user);
/*
displays the following
Serializing user object
*/
// unserialize user object
var_dump(unserialize($user));
/*
displays the following
object(User)[1]
public 'fname' => string 'Alejandro' (length=9)
*/
As you can see in the above script, each time an instance of the previous "User" class is serialized and unserialized, the PHP engine calls internally the "__sleep()" and "__wakeup()" methods, which display a simple message on the browser. Of course, it's possible to give a more useful and complex implementation of these methods, but hopefully the code sample shown above will give you a more clear idea of how to do this all by yourself.
Feel free to tweak all of the examples shown in this tutorial, so you can arm yourself with a better grounding in using these magic functions in PHP 5.
Final thoughts
That's it for now. In this fourth chapter of the series I provided you with a brief introduction to using the "__sleep()" and "__wakeup()" magic functions when serializing and unserializing objects.
Logically, as I said before it's possible to implement these functions in a more useful way, for instance for creating persistent objects that save themselves to a file or a database when they're serialized. Indeed, the possibilities are pretty numerous.
In the next article, I'm going to continue this exploration of magic functions that come with PHP 5. That particular tutorial will be focused on discussing the "__clone()" function.
Don't miss the upcoming part!