HomePHP Using the Sleep and Wakeup Functions to Serialize Objects in PHP
Using the Sleep and Wakeup Functions to Serialize Objects in PHP
Curious about how to serialize your objects inside your beautifully-crafted application? Look no further. Welcome to the second part of the series "Serializing objects in PHP." This set of three tutorials introduces the fundamentals of objects serialization, and teaches you some advanced concepts regarding this approach, such as using objects in sessions and storing them in database tables.
As you'll surely recall, over the previous article, I explained the basics of serializing objects in PHP. I showed some code samples that illustrated in a simple way the process of converting objects to their string representation (called serialization). I also showed how to reverse this process (that is unserialization), in order to restore these objects to their original state. In the several examples that you saw before, I also exposed some interesting concepts involved in object serialization, such as constructing objects that are capable of saving and restoring themselves via their own methods, which are commonly called self-saving objects.
As a matter of fact, one of the best things about serializing objects in PHP is that this fairly simple concept can be used as the starting point to tackle more advanced concepts, including those related to an object's persistence and its storage in database tables. In addition, if you've been working with sessions for a while, then you'll know that the PHP built-in session handling mechanism serializes and unserializes objects behind the scenes, whenever they're registered during a particular session, which means that object serialization is indeed an important topic that must be addressed appropriately.
Now, after refreshing the concepts that I deployed in the first part of this series, it's time to focus on the topics that I'll cover in this article, so you'll know what to expect before you continue reading. In this second part, I'll explain how to use objects in conjunction with the "__sleep()" and "__wakeup() magic functions respectively, in order to get the most out of them.
Having defined the topics for this new tutorial, let's move on and continue learning more about object serializing in PHP. Lets go!