Object Oriented PHP vs java

2004 Aug 9 at 08:35 » Tagged as :

If you have done any object oriented programming with PHP 4, you may have been left with the impression that it was an after thought. PHP 5 on the other hand includes several major improvements to the way that objects are handled. But there is a but. They appear to have been torn by a dilemma, to be or not to be like java.

In the older version Constructors used to have the same name as the classname - exactly the way it is in Java. You can still name your constructors in the same way but now the recommended approach is to name the constructor as __constructor which is kind of ugly.

Destructors are non existent in Java but they are part of the landscape in C++ and they are now a part of the PHP5 as well. Still it makes you wonder why destructors should be named as __destructor instead of with the class name prefixed with ~ as done in C++.

Another java like improvement is the __clone method, i have still not been able to determine if this is a shallow copy or a deep copy but as in java you can easily override this method to make it behave the way you want it to behave.

Other new kids on the block include abstract classes and method both of which seem to behave similar to their counterparts in Java and the same can be said of Intefaces.

How about parameter passing? in Java you will find that primitives are passed by value and objects are passed by reference, in PHP 4 everything was passed by value unless you explicitly passed by reference. Of course explicitly passing by reference is not something that you could do with java. The approach in PHP 5 is to mix the best of both worlds. Parameter passing now mimics the behaviour of java but you can use the good old ampersand when you want to.

We now have with us a group of classes that are 'built in' or a standard set of classes. Someone unfamiliar with PHP might not be impressed by their small number, but the strength of PHP lies in it's massive collection of functions which can do pretty much the same thing that java's 'inbuilt' set of classes can do. Some say more easily than with java.

The most notable built in class is the Exception class. Yes try - catch is now a part of PHP. The throw keyword is also available but I have not yet dug up any references to the throws keyword.

While still on the subject of keywords the private and protected keywords are also a part of PHP5, but because PHP 5 does not seem to have packages the so called default modifier (which is the absence of a modifier) is missing. In the absence of a modifer in php the class, method or property becomes public while in java it becomes what is commonly known as 'package private'. Interestinly I have not seen mention of the public keyword in the php docs.