I’m not getting how can serialize help me in writing efficient PHP application .
I am currently working on a stand-alone project on PHP where i have created a class to display a question feed which contains methods for throwing front-end HTMLs, and processing parts are also written in the same class.
Just for a example my outlined class is as follows
class QuestionFeed{
protected $vars;
public function throwHTML($filter_params){
........
}
public function InsertAnswers($answer_sanitized){
.........
}
}
And I have a page to display the front-part and a separate page for the insertion part. So naturally, I have to instantiate the class first at the display page and again at the processing page.
At this point, can serializing the object helps in any ways? And how?
Serializing an object is useful when you need to save the state of an object for later use. For example, you may have a user object that keeps user preferences, etc. Since the web is stateless, you will loose that object with each request. However, if you were to say serialize that object and save it in a session variable, that object could be reconstructed by unserializing it, thus, saving you from having to reconstruct a new object you already had during the last request.
On a side note: serializing and then unserializing an object will also accomplish a deep copy of an object where (clone) will only perform a shallow copy.
Example of serialization
This should print out the following:
So as you can see, I can restore my object to the way it was prior to serialization. Also, the __sleep() function is triggered before serialization begins so you can do any cleanup. And __wakeup is called after unserialization so that you can do some additional tasks after the object is restored.