This article is a response to a comparison made of PHP and Java by a Java programmer. This isn’t an attempt to start a flame war but rather to highlight that PHP is frequently misunderstood. And also to point out that PHP and Java can be very good friends...
Abdul Habra published an article in August 2002: Java or PHP.
He makes a list of comparisons between PHP, assigning point to each language as he goes. Whether you can assign scores in this kind of analysis I don’t know - personally I think it makes people page down to end and fail to read the rest of what he wrote.
This isn’t a criticism of his assessment. As he himself states: Please note that the author has more experience with Java than with PHP.. His article certainly provokes worthwhile analysis and here I’m going to try to point the things I feel are either subjective or incorrect.
level=”leve”>2. The PHP Tutorial Comparison 1. PHP is also capable of;
<? echo ('Hello World!'); ?>
<?=$var?>
<% echo ('Hello World!'); %>
<script language="php">echo ('Hello World!');</script>
. See PHP Basic Syntax.
2. Let’s not forget this syntax;
$var=<<<EOD <a href="http://www.php.net">PHP</a> EOD;
Using that syntax you can place anything you like in a variable without worrying about quotes. Cautions needs to be taken with the $ sign, which needs to be escaped.
3. Although Java conforms strictly to the paradigm that everything is an object, the end result is the same - PHP organises all incoming variables into global variables like $_GET, $_POST etc. Things like command line variables are accessed like $_SERVER[’argv’], much like C++. In other words there is a well defined structure for request/response. For PHP that structure is an array. For Java an object. Does it make any difference? And of course in Java you do this;
public class Echo { public static void main (String[] args) { System.out.println("Hello"+args[0]); } }
Global variables I’m coming to...
4. I agree that using global variables in your code is generally a bad idea but have the PHP engine set up global variables which you know the name of, such as $_GET. In my mind their the equivalent to environment variables such as “path” and as a result not a bad thing.
In PHP‘s configuration there’s a setting “register_globals” which if switched on, registers all request variables as global automatically (a very bad idea, especially for security: see Write Secure Scripts with PHP 4.2! for details.). With PHP 4.2.0 the PHP group opted to have this switched off by default - a brave but wise move.
5. This is basically a question of PHP‘s native functions, such as the String Functions. PHP implements a set of features which, for the web, is frequently richer than Java or .NET’s offerings. For example the Flash extension which allows PHP to generate complete Flash movies (with Actionscript) on the fly.
In Java you’re used to everything being an object. That the string functions are not encapsulated in practice makes no difference (just saves typing). PHP classes allow you to do the following for example;
class String { // Define our own strstr method function strstr ($haystack,$needle) { // Call the native function if ( strstr ($haystack,$needle) ) { return htmlentities ( $haystack ); } } }
Notice we defined our own strstr method. The end result is the same. PHP just saves you some typing.
6. PHP has every control structure available to Java (usually with the same syntax), from conditionals to iterations, built in.
7. See point 2.3
3. Language Features
1. PHP is loosely typed and arguably doesn’t need all of Java’s data types - many are required for the Java runtime to be cross platform.
In terms of programming, PHP‘s data types are not in the least bit limiting - i.e. there isn’t something you can do there with Java that you can’t with PHP.
2. For me that’s subjective again. For me it makes a PHP script easier to read than Java, that all variables are marked with a $.
3. This is really a strongly typed vs. loosely typed argument, which could lead to a massive debate - both have their pros and cons. If loose typing was simply bad, Perl would no doubt have died out long ago and Python wouldn’t have Java coders raving about it. My bottom line is programming needs care. If you’re not careful when you code, you will run into problems on large projects using either PHP or Java.
But hey, if you need it, you can use the set_type() function and type casting.
4. See point 2.4
5. Variable variables can be extremely powerful in PHP. For example;
$pageRenderer=new $_GET['mime'];
In the above example, say we have a URL like “index.php?mime=XML“. This makes the above code equivalent to;
$pageRenderer=new XML;
6. For me “Introducing a special function to define constants is counter-intuitive.” is subjective. This just follows from PHP being loosely typed.
7. Agreed. Java’s use of libraries make life alot easier that PHP in the long run, although require_once() can help deal with this and with PHP 5.0 and the Zend 2 engine, class namespaces should be introduced to PHP. Perhaps we’ll see packages as well, in future.
8. Actually this is does support overloading in a number of ways. Give that’s PHP is loosely typed, the way this is handled is different to Java and is, as a result, more flexible. Here’s one example where a method can accept any number of arguments;
<?php class Overload { function myFunc () { $vars=func_get_args(); foreach ($vars as $var) { echo ('Value: '.$var.'<br />'); } } } $o=new Overload; $o->myFunc('Hello', 'World'); ?>
It’s worth examining the manaul on Function handling functions.
There’s also the experimental overload() extension. Activestate have put this into good use with their PHP Simple Web Services API. Because PHP is dynamically typed, the generation of proxy classes can be done more easily that strongly typed langauges using the overload() function, without the requirement for an intermediate code generation step.
9. It’s worth noting, in PHP, that if you’re working with an API you constructed yourself you’ll know when to pass by value or reference. When using third party APIs, unless you feel like reading alot of code, you should in general always use references to instantiate objects, i.e.;
$object=& new Class;
10. We looked at this in 3.8.
11. It’s a handy one in PHP. For example;
<?php class MyEcho { function showFirst () { echo ('Hello '); } function showSecond () { echo ('World!'); } } $methods=array('showFirst','showSecond'); $e=new MyEcho; foreach ($methods as $method) { $e->{$method}(); } ?>
12. PS: if you really want to modify PHP to use periods for invoking methods, try Andrie Zimevski’s object operator patch
13. Multiple inheritance is one of those things coming to the Zend 2 engine. Do we need it? Perhaps not but it will be there soon anyway.
14. No contest.
15. Agreed - would be nice to have in PHP. Might encourge a PHP struts project perhaps?
16. This in one of the areas where PHP coders have to be creative right now, but it is possible to build your own interfaces in PHP. For example;
<?php class Temperature { var $value=0; function Temperature($value) { $this->value=$value; } function toCelcius() {} function toFarenheight() {} function getValue () { $return $this->value; } } class Celcius extends Temperature { function Celcius($value) { Temperature::Temperature($value); } function toCelcius() {} function toFarenheight($value) { return $this->value * 1.5; } } class Farenheight extends Temperature { function __construct($value) { Temperature::Temperature($value); } function toCelcius() { return $this->value / 1.5; } function toFarenheight($value) {} } ?>
If you wanted to for implementation of the of the interface methods, you might do this;
class Temperature { var $value=0; function Temperature($value) { $this->value=$value; } function toCelcius() { die ( 'Method toCelcius not implemented' ); } function toFarenheight() { die ( 'Method toCelcius not implemented' ); } function getValue () { $return $this->value; } }
Basically it’s down to the PHP coder to build them.
17. Right now you’re correct. API developers have to trust users not to access properties directly. Having said that, private member variables are another on the is of things to come with the Zend 2 engine.
18. PHP most definately does support inheritance and polymorphism!. We’ve already seen this in point 3.16, including overriding methods.
19. Again see point 16.
20. This requires a little creativity from a PHP developer again but using trigger_error() and your own error handler, you have all you need.
21. Fair enough. It’s not too common to need threading for web scripting though...
22. Again not something you need for a web scripting language - Beans become more useful in tiers behind your web presentation tier.
23. If you’ve ever tried running scripts in safe mode, it’s almost like total lock down. As PHP runs closer to the Operating System than Java (with it’s run time), it’s more the job of the System administrator to control what PHP has access to. Given that’s usually Apache and Linux, it explains PHP‘s comparitavely good record for security. Issues have been made of register globals in the past, catching out inexperienced developers. About the only other example worth commenting on was a vulnerability in PHP 4.2.0 and 4.2.1 which was dealt with swiftly as shown here
PHP in Summary
PHP has alot of critics, many of them having run into PHP around version 3.x, when there was no OO support. PHP has come on a long way since than and make no mistake, PHP has full support for Object Orientation. It doesn’t come with all the bells and whistles but three key elements of OO, namely Encapsulation, Inheritance and Polymorphism are all there. What PHP doesn’t do is enforce the rule “everything is an object”, and I would argue that for a web scripting language, that’s the correct approach to take. If object orientation was the answer to everything, why is the SAX API for XML still popular (which was origionally a Java API)?
Online, flexibility and rapid development is more important than theoretical paradigms. PHP‘s bottom line is always ease of use and following that, functionality. Try finding the native ftp, Flash or PDF functionality in ASP.NET for example...
PHP offers something for everyone. It’s evolved out of both C++ and Java and delivers the best of both worlds without the many of the headaches.
PHP and Java as Good Friends
Now it may seem like this is a defence of PHP over Java. That’s not the case.
Java’s problem on the web is it lacks a cheap, fast, reliable and widely supported environment to run in. As a result, it’s not being widely used for web deployment in anything but large enterprises.
PHP, on the other hand, became the most popular language on the InternetPHP can integrate with Java. That means you could use PHP as your presentation logic tier, in a J2EE. You have the choice of using SOAP (or some other XML protocol) or instead using the the Enterprise Java Bean API directly. Here’s a simple example from DevShed’s article on Using PHP with Java
A Java Class
import java.io.*; public class FileReader { public File LocalFile; // set file location public void loadFile(String FileName) { LocalFile = new File(FileName); } // return file size public long getFileSize() { return LocalFile.length(); } // check if file exists public boolean FileExists() { return LocalFile.exists(); } // return file path public String getFilePath() { return LocalFile.getAbsolutePath(); } }
A PHP client
<?php
$myClass = new Java("FileReader");
$myClass->loadFile("/home/john/test.txt");
if($myClass->FileExists())
{
echo "File size is " . $myClass->getFileSize() . "<br>";
echo "File path is " . $myClass->getFilePath();
}
else
{
echo "Sorry, the file " . $myClass->getFilePath() . " could not
be found"; }
?>
This is good news for everyone, providing Java developers an effective means to get their applications online while PHP gains greater acceptance in the enterprise as a viable solution. And as frequently PHP resembles Java, for someone with Java experience, learning PHP is a walk in the park.
Note that the PHP-Java extension is experimental at this time and it’s worth waiting for PHP 5.0 and the Zend 2 engine before giving it serious consideration.