PHPBuilder - Object Oriented Programming in PHP: The Way to Large PHP Projects Page 7

RSS Twitter

Object Oriented Programming in PHP: The Way to Large PHP Projects - Page 7

by: Luis Argerich
January 25, 2008

Advanced OOP Techniques in PHP

After reviewing the basic concepts of OOP I can show you some more advanced techniques:


PHP doesn't support persistent objects, in OOP persistent objects are objects that keep its state and funcionality across multiple invocations of the application, this means having the ability of saving the object to a file or database and then loading the object back. The mechanism is known as serialization. PHP has a serialize method which can be called for objects, the serialize method returns a string representation of the object. However serialize saves the datamembers of the object but not the methods.
In PHP4 if you serialize the object to string $s, then destroy the object, and then unserialize the object to $obj you might still access the object methods! I don't recommend this because (a) The documentation doesn't guarrantee this beahaviour so in future versions it might not work. (b) This might lead to 'illusions' if you save the serialized version to disk and exit the script. In future runs of the script you can't unserialize the string to an object an expect the methods to be there because the string representation doesn't have the methods! Summarizing serializing in PHP is VERY useful to save the data members of an object just that. (You can serialize asociative arrays and arrays to save them to disk too).


=new Classfoo();
// Save $str to disk

//...some months later

//Load str from disk

You have the datamembers recovered but not the methods (according to the documentation). This leads to $obj2->x as the only way to access the data members (you have no methods!) so don't try this at home.
There're some ways to fix the problem, I leave it up to you because they are too dirty for this neat article.
Full serialization is a feature I'd gladly welcome in PHP.

« Previous Page
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Luis Argerich



(Maximum characters: 1200). You have characters left.