5/4/04
<< 72 Squared WeblogOOP vs. procedural programming in PHP
I've heard arguments on both sides of the OOP vs. procedural discussion. I ran into a programmer at the coffee shop near my house the other day. I asked him about all of the OOP features offered in the soon to be released PHP5. He thought it was a waste to try to make PHP behave in an object oriented manner. He was a Java programmer, and used php as a way to deliver the front-end with WebObjects handling the backend. In his opinion, PHP was written as a procedural language and should be stay that way.
I'm not so sure. OOP is such a useful concept. But there are a number of pitfalls. Object-Oriented Programming was popularized in languages such as Java. Many programmers make the mistake of trying to translate the code they wrote in Java directly into PHP. Big mistake. PHP is a very different animal, and although it takes advantage of many of the features of OOP, it does not offer persistent objects in the same way. Projects needed to be coded in a lightweight manner. Java allows objects to be instantiated once and then reused over and over again for many different clients. PHP does not behave in the same way. Each time a request is made to the webserver, PHP reinstantiates the object to use only for the lifetime of that individual request. This becomes very inefficient when trying to instantiate large, complex or interrelated objects. But for many projects, It makes complete sense to use OOP. Object oriented programming can be very lightweight and efficient if done properly. My database abstraction is only 236 lines of code but it provides me with all the features I need to easily connect to any database I need through a standardized set of methods. This comes through careful code refactoring, and a clear set of objectives for the class. When I was first learning OOP I came across an article that said "DON"T MAKE GOD CLASSES". In other words, don't try to make a single class that does everything. Make small, lightweight classes that do a specialized job efficiently and extend the base classes. This is true, and it is the key to effective OOP for PHP.