PHP vs. Java which is a better Object Oriented Language?

I left Microsoft Technologies and shifted to Open Source around July 2006, that’s when I was first introduced to the LAMPP Stack (Linux Apache MySQL Perl PHP), though I started my journey with Perl but gradually moved towards PHP. Open Source Technologies and PHP have been my bread and butter since then, but I could never admire PHP like I admired C, C++ and Java, always felt limited even when I was applying OOP concepts with PHP but yes in spite of this I loved PHP arrays and the wide range of array functions. My first PHP OOP project happened in December 2007 where I got introduced to Zend Framework as well, since then I’m still in love with ZF but ironically still not fond of PHP, especially PHP OOP! PHP’s weaknesses as an OOP over Java repeatedly kept disturbing me, and this became my favorite interview question for any candidate who claimed to have PHP and Java OOP concepts. I would say about 25-30% of the people could hit chord somehow but rest failed miserably.

In the first section of this article I’ll discuss about the salient features of Object Oriented Programming, next section I’ll address the broad differences between PHP & Java, and in the final section I’ll try to lay down the key weaknesses of PHP OOP over Java.

Object Oriented Programming

Conventional or traditional programing using a high level programming language like C is termed as Procedure Oriented Programming where things happen sequentially, i.e., reading (input), computing, printing (output) take place in sequences. Functions or procedures are written to accomplish all kinds of computations, some functions are system defined and some are user defined.

Object oriented programming emphasizes more on data and data structures rather than functions or procedures; they are tied with the data on which they operate. Data is defined as objects and objects are supported by member functions which are part of the data structure. Object oriented programming takes a bottom-up approach in contrast with the top-down approach of procedure-oriented programming where small modules consisting of data and member functions unite to implement a large application.

Concepts or Principles

  • Objects
  • Classes
  • Data Abstraction & Encapsulation
  • Inheritance
  • Polymorphism
  • Dynamic Binding
  • Message Passing

Objects

Objects are the building blocks of any object-oriented system, they are the smallest units created on run-time and they represent a definable entity like a person, a car, an employee, an animal, a song, an item, any custom data defined by the user. Any problem that has to be solved programmatically must be analyzed in terms of objects if we are adopting object-oriented programming approach. While defining the objects we must try to map them with real life objects / items. When objects are created on run-time memory is allocated to store them, objects are somewhat similar with data structures in C but unlike data structures objects have member functions / methods associated with them which manipulates them and also lets them interact / communicate with other objects.

Classes

As I said objects consist of data and member functions to manipulate the data, classes are used to define the object and the functions. A class is like a custom user defined variable type with certain attributes and functionality attached to it. Objects are singular or multiple instances of a class. So, if person is a class with attributes like name, dob, height, weight and member functions like age() and bmi() then age() will calculate the age of each person based on dob and current date and bmi() will calculate their body mass index based on height and weight.

Data Abstraction & Encapsulation

Class is a combination of data and functionality and this very feature is termed as Encapsulation. Data that belongs to a specific class cannot be accessed by any outside function or the program by default which is not part of that class, i.e., only member functions can access the data of any class unless access is given specifically. This insulation of data from the program is termed as Data Hiding or Information Hiding. Also the algorithm / logical explanations of the member functions are hidden from the outside program of any class; this feature is referred as Abstraction. As Classes use the concept of Abstraction they are called as Abstract Data Types (ADT).

Inheritance

As the term suggests a Class can inherit the properties of another Class. It can implement the concept of hierarchical classification, e.g., Gorilla is type of Ape which is again a type of Mammal. So, all Gorillas will inherit the common properties of Apes and all Apes will inherit the common properties of Mammals. The concept that inheritance implement is Reusability, i.e., once we have defined the properties of Mammals and we don’t have redefine / re-write then in Apes all we have to do is establish inheritance between Mammals and Apes such that Mammals act as the parent Class of Apes, further we’ll have to append additional properties of Apes to extend its functionality. The parent Class is called as Super Class and the child Class is called Sub Class.

Polymorphism

It’s a Greek term which means “the ability to take different form”, Polymorphism is implemented in form of Function Overloading and Operator Overloading. Using Polymorphism it is possible to make a certain member function or an operator act differently based on the data input provided. The + operator can produce sum of two numbers if the operands are numeric in nature and the same operator can produce a concatenated string is the operands strings. Similarly if we define a function called getVolume() which will compute volume of a cylinder if for inputs radius and height and the same function may be re-defined to compute volume of a cube for input edge. Polymorphism is extensively used to implement inheritance, e.g., both cylinder and cube are 3D Objects so they are part of the same Super Class but since their volume is computed differently using different data points so two inherited Sub Classes were required to be defined.

Dynamic Binding

Binding refers to the linking of a procedure call with the code to be executed in response to the call, Dynamic Binding (also called as Late Binding) means that the code to be executed for a particular procedure call is not known until it is called in run-time. This is associated with Polymorphism and Inheritance. A function call associated with a polymorphic reference depends upon the dynamic nature of that reference. In the above example the method getVolume() will calculate the volume of cylinder or cube or cone or prism or sphere will depend on the call reference and getVolume() method will have to be re-defined for each type of 3D Object.

Message Passing

The process using which objects communicate with each other is called Message Passing. It simply means that (at a very abstract level) the fundamental mechanism of program execution is, objects sending each other messages. Name and structure of these messages is not necessarily fixed beforehand in the source code and can itself be additional information. C++ and Java implement a limited version of message passing through method calls where number of messages is limited to the number of methods declared in a class.

PHP vs. Java

Java was originally developed at Sun Microsystems around 1995. Java applications are compiled to an intermediate byte code, which is run by a virtual machine (JVM). PHP was born in the same year, while Java was meant for client applications and in-browser applets; PHP was specifically created for web as a server side scripting language to embed in HTML pages.

PHP and Java have a vast array of differences, though PHP has borrowed its Object Oriented paradigm from Java even when it comes to OOP using PHP the differences are significant.

Typing

Java is strongly typed PHP is not. Each and every variable in Java must have a declared type, while Java is built over static typing PHP uses dynamic typing; in PHP variables assume the type of value contained in them and they can change the type implicitly to support type-casting and conversions. This makes a huge difference to method signatures; you can only force method parameters to be of a certain class or interface or an array but you cannot type hint for primitives. So, public function myMethod (int $foo, boolean $bar){} is invalid and will throw a parse error.

Return Type

PHP does not require (or even support) specifying the return type of a function.

Execution Model

PHP classes, functions and data structures, when they do not leverage external infrastructure like cache or database servers, are created in a script and they are garbage-collected at the end of the request. Java applications are instead kept in memory between requests, and the architecture of these two kinds of applications is fundamentally different from each other. Though, one execution model cannot be considered superior to the other. PHP pulls in execution only what it needs, and it pays back with the inability to run periodical tasks such as cron jobs. Java applications can start multiple threads, but their management is much more complex, from the compiling phase to the deployment which includes servlets reloading.

Infrastructure

PHP is easy and simple to deploy in its core form i.e., .php scripts, but using core PHP is not sufficient for the developer to build standard infrastructure and there has to be some framework, which builds the same features over the simple PHP interpreter. Ironically, these framework are similar to Java ones; for example Zend Framework’s controllers are the equivalent of servlets: classes with a standard constructor that extend a common base class and act on a request object to produce a response one.

Java has less native features built in the language, as it is not strictly oriented to the web, but it has them in frameworks, which adhere to a standard, the servlet containers. PHP capabilities are hindered by the absence of standards.

For instance, the web.xml file in WAR packages, which represent a web application, define routes to map URLs to servlets.

Object-oriented programming

PHP 5 borrowed its object-oriented paradigm from Java, which is the standard implementation of an object-oriented language today. After the release of PHP 5, a key point in the introduction of a serious object paradigm, PHP is evolving towards OOP and has borrowed more from Java products: Doctrine 2 is an object-relational mapper inspired by Hibernate and JPA; phpDocumentor is built on the example of Javadoc; PHPUnit is one of the xUnit products, which derive from the original JUnit.

  • PHP classes do not have final fields, although what would be a static final field in Java is a const in PHP. EDIT: A const in PHP is more limited than a static final in Java as the latter can be an array or object instance, whereas the former must be a constant value (number or a string, essentially).
  • “Overloading” in PHP does not mean the same as it does in Java. In Java, it means specifying multiple methods of the same name, but with a different set of parameters: public void myMethod(int foo){}; public void myMethod(float foo){};
  • In PHP, it refers to the dynamic creation of properties and methods using the __get(), __set() and __callStatic() “magic” methods. See the PHP manual for a description on their use. Java-style method overloading is impossible in PHP and an attempt to re-declare a method (with or without a different set of parameters) will fail.
  • May be obvious to some, but in PHP you use :: to access static methods and properties and -> to access instance ones, but in Java . is used for both.
  • PHP doesn’t have packages, but it does have namespaces.
  • As of PHP5, constructors in PHP are not supposed to be methods with a name that matches the class, like in Java, but the magic method __construct() should be declared instead, although the PHP4 style is supported for backward-compatibility. Also, PHP has a destructor method named __destruct().
  • In Java, all classes inherit from Object, but there is no such generic super-class in PHP.
  • Even when maximizing the amount of OOP in a PHP script, it still relies on a procedural flow; there’s no class-level entry point like in Java (i.e., public static void main(String[] args) or public void init() for applets).

References:

Java vs. PHP
Stackoverflow