In spite of my own fears and warnings from others about the limitations of using the object-oriented features in PHP 4, I plowed ahead this week. In the reporting system I’m working on, I finally got to a point where I needed more structure than include files and functions. Object-oriented systems have three characteristics, encapsulation, polymorphism, and inheritance. I won’t go into the boring details of what each of these characteristics involve, but suffice it to say that I’m only using the object-oriented features of PHP to take advantage of one of them — encapsulation.
At this point in my programming career, I find it nigh on impossible to deal with complexity without bringing encapsulation into the picture. A few weeks ago, I mentioned a problem I was having involving reports that include outer joins. Once I had solved the problem, I realized that I had a whole bunch of code that was used to convert the represenation of the data in the database to the representation used in the reports. Then I had a whole different bunch of code that’s used to create the where clauses for the queries that generate the reports. In the Java world, all of that stuff is hidden away in nice private methods so that they aren’t exposed to the rest of the application. Unless you start travelling down the path of object-oriented PHP, that same functionality pollutes the core namespace of your application. The functions are bad enough, but the real problems come into play when it comes to variables. You get into a situation where you pass ever increasing numbers of arguments around, you start using the
global keyword everywhere, or you start abusing associative arrays really badly. In any case, you are liable to run into trouble.
There are two downsides to OO PHP. The first is that it’s obviously an add-on. My core logic isn’t object-oriented — it lives in a page. It just brings objects to the party as it needs them. The second is that the syntax is pure torture (at least in PHP 4). I still don’t fully understand all of the implications of using references to pass objects around by reference rather than by value, and the necessity of using
$this everywhere within a class is painful. Finally there’s the matter of not getting compile-time checking when you reference a property in an object like
$object->property. I still don’t know what that’s about. In fairness, I haven’t investigated PHP 5, which may address some or all of these problems.
In any case, in spite of the awkwardness of OO in PHP 4, I recommend its use if you want to stay sane.