Object serialization in PHP is very easy, and can be used for a variety of different purposes. It can be used to perform some fairly complex operations, in fact. This article, the first of a three-part series, introduces you to object serialization and a number of the tasks for which you can put this approach to use.
Anyone who has been using PHP object-oriented programming for a while knows that object serialization can be a useful approach, which can be utilized for different purposes. Whether certain objects need to be stored as a string representation of their methods and properties in a database table, or maintained “alive” across several HTTP requests via a session mechanism, in all these cases serialization, and its counterpart, unserialization, play an undoubtedly relevant role.
Certainly one of the best things about serializing objects is its extreme ease to perform, trust me. Using the popular combination of “serialize()/unserialize()” PHP native functions, it is perfectly possible to get an object serialized and vice versa, during the execution of a PHP application, without the need to appeal to sophisticated programming techniques.
The truth is that when it comes to serializing objects, PHP makes the whole process a no-brainer task. However, despite its ease, object serialization can be used in different situations, in order to perform more complex operations, such as making an object persist during different web pages, or taking advantage of the “__sleep()” and “__wakeup()” magic functions, which are called automatically when an object is serialized and unserialized respectively.
As you can see, serializing objects in PHP is a very useful approach, which deserves at least a closer analysis. That’s why over the course of this three-part series, I’ll take an in-depth look at the more relevant topics regarding the serialization of objects, starting out with the basics, and progressively introducing more advanced concepts, like using objects in sessions, and storing them in database tables.
What should you expect from this series? By the end of it, you should be equipped with a decent knowledge of how to serialize/unserialize objects without losing their methods and properties during the transition, as well as constructing persisting and session objects, and much more.
Having established the goals for this series, let’s introduce ourselves to the vast territory of object serialization in PHP. Let’s go!