HomePHP Page 4 - Using Inheritance, Polymorphism and Serialization with PHP Classes
Serializing - PHP
If you are working with classes in PHP, you will sooner or later encounter inheritance, polymorphism, and serialization. The ability to use these three will help speed up your code writing. This article covers how to use them, and more.
Objects by their very nature are very difficult to manage as strings or numbers. This makes it difficult to store them in a database, pass along to a script, or use them generally for storing values, such as, for example, setting one as a cookie. To solve this problem, PHP has a function called serialize(). This function takes a variable and turns it into a more manageable version of itself. The syntax of this function is:
And to return the variable to its original state:
Both functions are a bit like encryption. If you want to hide a text you turn it into something unreadable, and then if you want to show the text you return it to its plain text state. This is more or less what serialization is about.
When using these functions make sure to include the class definitions on the page that you call unserialize().
Both functions look for two special functions when serializing objects:
serialize() checks to see whether your class has a function with the name __sleep. If that function is present, it will be run prior to any serialization. It is responsible for cleaning up the object and then returning an array that includes the names of all variables of that object that should be serialized.
The purpose of the __sleep function is to close any database connections that an object may have, commit pending data, or perform similar cleanup tasks. The function is useful for saving large objects.
unserialize() checks for the presence of a function with the name __wakeup. If present, this function can reconstruct any resources that object may have.
The intended use of __wakeup is to re-establish any database connections that may have been lost during serialization and perform other reinitialization tasks.
While coding with functions and objects makes programming easy, it can also slow down code execution, particularly on large projects. So take care when deciding to use it.