Basic Java and PHP Syntax Differences

PHP and Java are generally used for vastly different purposes. However they share a fairly common syntax based on C++. If you use both, here are some differences to remember.

A simple PHP function might be public function add_three_numbers($x, $y, $z) { $answer = $x + $y + $z; print('foobar message'.$answer."\n"); return $answer; } ... $sum = $this->add_three_numbers(1, 2, 3); while the Java equivalent is public int addThreeNumbers(int x, int y, int z) { int answer = x + y + z; System.out.println("foobar message" + answer); return answer; } ... int sum = this.addThreeNumbers(1, 2, 3);

The differences in the preceding functions are:

FeaturePHPJava
string quotessingle ' or double quotes "ONLY double quotes "
string concatenation.+
variable prefix$n/a
variable typeloosestrong ie. int, float, string, etc
function invocation-> (:: for static methods).
function return typen/aneeded - void, int, etc.
function signature'function' keywordn/a
function namingmixed - camelCase or underscoresusually camelCase
printing to consoleprint, echo, print_r, var_dumpSystem.out.println, System.err.println

Another key Java concept is the package system, using package, import statements to get qualified namespaces.

In PHP, namespaces are new to 5.3, but not yet widely used. require, require_once, include, include_once statements are used and everything is global.

Add new comment