Compare Java, C++ and PHP class features

Java, C++ and PHP all support similar OOP concepts like class/object. Sometimes it can be frustrating, however, for programmers to apply similar OOP thinking into different languages. The reason is that there are some subtle differences between them in terms of OOP design, besides obvious language syntax difference. By doing the apple-to-apple comparison, one can remember those features much better. Here I am starting to compile the list of OOP features that are different between Java, C++ and PHP. Hopefully this list can be more comprehensive as time goes by.

1. Class method

1.1 Method overloading
Java and C++ class can have multiple methods sharing the same name but with different parameter signatures, i.e., method overloading. Unfortunately, PHP can’t.

A consequence is that Java and C++ throws error when calling a class method without matching its parameter signature, while PHP will just take it happily without warning. Such loose behavior of PHP can surprise Java programmers. For example, the following PHP code runs just fine.

class MyTest
{
  public function display($id)
  {
    return $id;
  }
}
$t = new MyTest();
echo $t->display("hello", "world");

1.2 Default parameter
PHP, C++ support default parameter values in method, while Java doesn’t. Java programmers may want to use the Builder Design Pattern instead.

1.3 Static method
While Java can call a static class method using either a class name or an object instance, PHP and C++ have to use the official class name ONLY.
Another minor syntactic difference is that, Java use “.” while PHP and C++ use “::” as the delimiter.

Leave a Reply