Agile Zone is brought to you in partnership with:

I am a programmer and architect (the kind that writes code) with a focus on testing and open source; I maintain the PHPUnit_Selenium project. I believe programming is one of the hardest and most beautiful jobs in the world. Giorgio is a DZone MVB and is not an employee of DZone and has posted 635 posts at DZone. You can read more from them at their website. View Full User Profile

And now instead, 5 things Java envies PHP for

  • submit to reddit

Disclaimer: I do not want to start a religion war on Java vs. PHP. You know the old saying that we should learn a new programming language every now and then? The purpose is to get a fresh perspective and collect new ideas that we can use in our preferred platform. Every language can teach us something new, even if Java is already the standard for programmers education.

The comparison is only on web applications and dynamic websites, as PHP does not compete on the desktop. I am a PHP programmer, but I work in Java on university-related projects. If you notice something is missing from the comparisons in this list, feel free to comment and complete my depiction of Java features, and of PHP too.

Let's start.

You can't produce memory leaks

A shared nothing environment can sometimes be an hindrance, but it's definitely helping for performances and robustness. Everything in PHP is closed and destroyed at the end of the script: even if a library or resource you cannot avoid using leaks memory like there's no tomorrow, that memory will be freed at the end of the script. There is also a memory_limit directive, by the way, in case the script is doing something heavy like database population.

Even in the case of infinite recursion, a segmentation fault happen in the process currently running, which crashes. The next request can be served seamlessly, as if nothing has happened. No application state means it can't be left in an awkward state, and as some thoughtful commenters state in the comments to the previous article, no need for locks and synchronization. Multithreading in PHP is simply the use of multiple scripts (asynchronicity must be managed out of the script.)

No compilation required

I know, IDEs take care of everything and when you hit any keystroke, they simply recompile everything is out of date. However, in PHP there is no compilation step required by the programmer, and for example you run tests on the included source files. Libraries are shipped as source code and when they fail it's a matter of seconds to go to the particular line which generates the error.

The absence of explicit compilation does not mean that there are no compile-time checks: every script is compiled Just In Time before execution, and the opcodes (equivalent of bytecode) can be cached in production environments. Thus, a script with syntax errors cannot be executed at all; a class extending a not existing parent class cannot be defined. And so on. Without explicit compilation, there is one step less in testing, CI, and deployment (unless you are Facebook and invent HipHop). As far as I know, Java JIT compilers go from bytecode to native code, but they do not start from source code.

Unified platform

Choices are usually good for developers, but alternate implementations shouldn't be named with the same package and class name.

For example, when I was working with OSGi, I found out a show stopper issue was caused by the usage of a org.w3c.dom package which was different from the expected one, since Xerces wanted to use its own org.w3c.dom.Document, different from the one included with the JVM.

I have never seen duplicate class names in PHP code, even before namespaces were introduced. Maybe the scale of object-oriented code in PHP is not so high to produce such conflicts, but when you instance a class you know exactly what code you are referring to; and its source code is always there for inspection when an abstraction fails.

Database (and more) batteries included

Every supported relational database driver is usually enabled, and shipped with the binary PHP package. You can disable loading of the extensions you do not use, but enabling MySQL or Postgres for PDO is usually a matter of uncommenting a line in php.ini. No Jars to download or to pick with Maven during the build, no multiple versions incompatibilities.

And it's not only a matter of talking to a database. Just try reading a file:

File file = new File("C:\\MyFile.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;

try {
fis = new FileInputStream(file);

bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);

while (dis.available() != 0) {


} catch (FileNotFoundException e) {
} catch (IOException e) {

compare with

<?php echo file_get_contents('MyFile.txt'); ?>

I know there's Apache Commons, but do I have to download and link an external library just to read a file?

I know also performance can be affected with the PHP solution, but we have fread() and similar functions if you really want to read in blocks.

Let's try with an XML file:

try {
File file = new File("c:\\MyXMLFile.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
NodeList nodeLst = doc.getElementsByTagName("employee");

for (int s = 0; s < nodeLst.getLength(); s++) {

Node fstNode = nodeLst.item(s);

if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
System.out.println("First Name : " + ((Node) fstNm.item(0)).getNodeValue());

} catch (Exception e) {

compare with:

$xml = simplexml_load_file('MyXMLFile.xml');
foreach ($xml->employee as $e) {
echo "First name: ", $e->firstname, "\n";

Again, built in the language. Let's skip JSON...

Shared hosting

Shared hosting is a bittersweet characteristic of PHP. It's cheap: in Italy you can get an host with 4 MySQL databases for less than 10 Euros, and also for free if you accept a subdomain (prices go up with required performances, technical support, and services like SSH). The money mostly covers the domain name registration. The same machine can support many websites, as nothing is in execution until a user requests a page.

It's easy to deploy to: it only needs a phpMyAdmin instance, to manage the database via browser, and some file transfer mechanism (back in the old days, FTP, but also svn or git if there is shell access). Zero configuration external to your own application and database: once you have a build, you can just drop it in the right folder, or change a symlink.

The barrier to entry is very low, which means also the average PHP programmer won't have read all of Dijkstra papers. PHP is often treated as a toy language due to the results obtained by the low-end segment of programmers, but shared hosting is one of the key points of PHP's popularity.

Published at DZone with permission of Giorgio Sironi, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)


Balint Persics replied on Tue, 2011/01/25 - 8:54am

You are mixing the programming language (which is basically some form of formar grammar with semantics) with libraries (or APIs if you prefer). SimpleXML is a library as is Apache Commons. This is not part of the PHP language. Same for JSON and databases. Yes, most of the PHP deployments out there have a lot of libraries enabled by default but that does not mean it is better. "but enabling MySQL or Postgres for PDO is usually a matter of uncommenting a line in php.ini. No Jars to download or to pick with Maven during the build, no multiple versions incompatibilities." What it really does mean, that PHP comes with a lot of libraries prepackaged. Same for Java deployments: If you have the jars in your classpath, you can use them without any configuration. Some thoughts on memory leaks: It is caused by a shared-nothing architecture, not by PHP itself. You can easily implement a servlet container which discards every object for every request but it has huge performance drawbacks. That's why most servlet containers do not have this. But it can be implemented.

Wojciech Kudla replied on Tue, 2011/01/25 - 8:57am

Obviously, you did not get into OSGi very deeply. If you did, you would know about package version scoping or configuration properties such as org.osgi.framework.bootdelegation or org.osgi.framework.system.packages, that would solve your "show stopper". There is no point in correcting your other conclusions. Please, be more solid next time or do avoid refering to knowledge gained from "university-related" projects.

Andrea Del Bene replied on Tue, 2011/01/25 - 9:22am

Giorgio your example about file reading is quite outdated! The right way to load a text file is using BufferedReader, i.e.

BufferedReader in
= new BufferedReader(new FileReader(""));

Method readLine from class DataInputStream is deprecated (and as you pointed out is more verbose).


Raphael Miranda replied on Tue, 2011/01/25 - 9:28am

Java is supported in Google App Engine and several other cloud hosts out there where hosting even an 'enterprise' java app is very cheap(depending on your traffic obviously). About the Unified platform problem, you can do java proceduraly too, stuffing java inside your jsps, like we did back in the 90s.

Yaman Asdasd replied on Tue, 2011/01/25 - 9:35am

Java is a core programming language and you can do more than PHP environment as a language. This simple process could be easier with PHP but if you want to execute a bit complex process like a xml to object conversion how can you do this with PHP. It is just an example i wanted to tell that you have a powerful toolbox by using Java that's why this kind of easy file processes is harder at Java.

Jason Mulligan replied on Tue, 2011/01/25 - 10:12am

@Yaman Asdasd that's rather easy with PHP. XML -> Obj: $obj = simplexml_load_string($string); if you want to change the casting, a simple json_decode(json_encode($obj)) will get you to a stdClass Object. Going the other way is also easy. Object -> XML can be done by creating a DOMDocument instance, and either get_class($obj) for the root element, or iterate and set the key:value pairs with appendChild() on the root if it's a stdClass object. These editorials over simplify and cause misdirection. I would've touched on the fact that PHP can run on embedded devices like cheap NAS/routers/etc with opensource community firmware hacks; no one every puts a tomcat install on slow hardware on purpose.

Balint Persics replied on Tue, 2011/01/25 - 10:25am in response to: Yaman Asdasd

"but if you want to execute a bit complex process like a xml to object conversion how can you do this with PHP" That's what SimpleXML is for. It's like JAXB but only for reading. File processing by line, or every other problem: it is not harder nor easier on each of these platform. They are just using different concepts. Java's solution is far more general than PHP's, that's why it take more lines of code to accomplish the same thing. But with Java's approach, a broader set of problems can be solved with those classes. file_get_contents servers only one purpose. You can see the point behind the library support for each platform: Java targets general programming problems, PHP deals with web-site scripting (yes, I know there are extensions for daemons, GTK and other tools, but really, who uses them?). The target audience is different for the core libraries. The languages themselfs (so the formal grammar and the semantics) are similar and both Turing complete, they are both OOP-supporting languages. Not so much difference in general. In the details, one can find many differences: Java has a memory model (in reality, a model for correct multi-threading), Java has a security model, and so on. They are same in the very basics (every imperative language is same for the basic concepts: loops, function calls and conditional code paths), but in details, they are different. If you only use the basic blocks, you are happy to go with both languages. The hard thing is to master the things beside those building blocks.

Balint Persics replied on Tue, 2011/01/25 - 10:30am in response to: Jason Mulligan

Most of the embedded devices support direct Java bytecode execution since modern ARM architecture support the Jazelle technology. That is how JavaME works on far more restricted (in terms of processing power and available memory) devices, such as feature phones, compared to SOHO routers. It would be interesting to see a full JVM+Java SE stack running on ARM devices (no, Dalvik is not a JVM)

Alef Nula replied on Tue, 2011/01/25 - 12:02pm

The text-file example can be implemented with java.util.Scanner.

Scanner scanner = null;
try {
	scanner = new Scanner(new File("C:\\Windows\\win.ini"));
	while(scanner.hasNextLine()) {
} catch (FileNotFoundException e) {
} finally {
	if(scanner != null) {

 And the XML example can implemented in a substantially shorter manner when using XPath:

XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList) xPath.evaluate("//firstName", new InputSource("MyXMLFile.xml"), XPathConstants.NODESET);
for(int i = 0; i < nodeList.getLength(); i++) {


Giorgio Sironi replied on Tue, 2011/01/25 - 1:42pm in response to: Balint Persics

Can it also discard static fields contents? While Java targets multiple devices and have multiple implementations, there is no layer of abstraction between language and platform in PHP (nor I can imagine someone wanting to replicate our giant procedural Api). When a new feature is implemented in the core, you get it at the next release, and the language specification *is* the C source code.

Giorgio Sironi replied on Tue, 2011/01/25 - 1:43pm in response to: Andrea Del Bene

The example came from the first result in the related Google search (but Google is not so efficient lately).

Giorgio Sironi replied on Tue, 2011/01/25 - 1:43pm in response to: Andrea Del Bene

The example came from the first result in the related Google search (but Google is not so efficient lately).

Giorgio Sironi replied on Tue, 2011/01/25 - 1:50pm in response to: Yaman Asdasd

I think data mapping between XML and objects is a quite complex task, that shouldn't be solved by code generation. In the use cases of PHP (web services) the most important thing is often get a subset of the data out and discard the rest.

Jonathan Fisher replied on Tue, 2011/01/25 - 2:14pm

Wow, this post is just pure flamebait. Java is more all-purpose than PHP, so of course PHP might do some web-oriented things better. However, PHP does not power telecom switching systems, claim processing systems, nor financial transaction systems in the traditional enterprise. PHP supports just a subset of what Java does, so these types of posts are just plain dumb.

Balint Persics replied on Tue, 2011/01/25 - 2:18pm in response to: Giorgio Sironi

"Can it also discard static fields contents?" The lifetime of a static field is the lifetime of the enclosing class whose lifetime is the lifetime of the ClassLoader loading the class. Classloaders can be created and discarded except the boot classloader whose lifetime starts and shuts down with the JVM instance. "there is no layer of abstraction between language and platform in PHP" Yes, there is. There is always an abstraction between a language and a platform. Here is the description of the PHP language although it is clearly not a well-formed specification. Everything else documented on the website is the PHP Platform. For Java, there is the Java Language Specification (with much better defined semantics than in PHP) and the various JSR-s defining the platform via the JCP (for example JSR-336 defines the Java SE 7 platform). For PHP, it is such a mess. Since there is no clear specification for the platform or the language, no one can implement it independently from the source code. "(nor I can imagine someone wanting to replicate our giant procedural Api" The Java SE and EE API-s are much bigger, yet there are several independent implementations.

Christian Schli... replied on Tue, 2011/01/25 - 3:37pm

Sorry, but this is one of the most naive file reading Java code I've seen for a long time.

You're completely missing the point of the decorator pattern: You're not supposed to close() all streams, just the top level decorator and you should make sure to do it in a finally-clause like so:

BufferedReader reader = new BufferedReader(new FileInputStream("foo"));
try {
  // ...
} finally {

That's it.

Cloves Almeida replied on Tue, 2011/01/25 - 10:25pm

Batteries not included?


1) wget -P lib

2) add the JAR to the classpath.

Really, how hard is that? And no Maven in either hand!

Repeat the process for Commons IO for easy file reading;  JDom/XStream/SimpleXML for simple XML manipulation...

PHP's magic is the shared nothing architecture and being newbie-friendly. While it provides nice scalability out-of-the-box, 99% of the projects won't demand it - the remaining 1% has budget to pay for specialists). And you don't want newbies messing with your mission-critical app.

(I must concede that back in 2000 Java was pretty confusing, touting EJB's and all that - too bad PHP and not Python filled the void)

Dewald Botha replied on Wed, 2011/01/26 - 2:04am

Look, apples with apples - Sure, Java does enterprizey things.  Sure, PHP is more for the web - but is that really a XOR situation.

The thing is, since the entry level to Java is higher than that of PHP, you'd get more inexperienced developers just playing around in PHP which results in sub-standard coding and practices.   That being said, I have seen some shocking Java code - I have also witnessed horrible Python and Ruby code that will make you go, 'Jikes'.

So ofcourse for every 10 'beginner' PHP developers you'd only get 1 'beginner' Java dev.  I think past are the days where software engineers should be boxed into a language.  Rather say, I'm a software developer that uses PHP/Java/Python/Ruby/Erlang etc... to apply my trait because of [whatever language's] awesome power.

Also boxing a language could be a horrible thing.  You could use Java to write a web based CMS - and I'm sure you can use PHP to drive a banking site.  Each of the languages has its pitfalls, the idea is to explore all avenues and then make a decision on that.  That is why I say, 'apples with apples'.

Just my 2 cents.


Giorgio Sironi replied on Wed, 2011/01/26 - 6:55am in response to: Balint Persics

Being able to discarding static contents would definitely be handy also in PHP, for running test suites. :)

The fact that it is a mess was my point: the Api is a mix of procedural and OOP code, and apart from HipHop there are no alternative implementations. So when we talk about PHP, the language is just "what /usr/bin/php accepts".

Giorgio Sironi replied on Wed, 2011/01/26 - 6:59am in response to: Cloves Almeida

Add that the Jar must be imported on version control or added to the build, and that should be multiplied for N libraries. Then it should be upgraded when new versions are out, or to fix bugs. Using it in an OSGi environment means also the IDE must rebuild its classpath from the OSGi metadata. There are many hidden costs to the use of external libraries.

Mladen Girazovski replied on Wed, 2011/01/26 - 8:38am in response to: Giorgio Sironi

 Add that the Jar must be imported on version control or added to the build, and that should be multiplied for N libraries. Then it should be upgraded when new versions are out, or to fix bugs. Using it in an OSGi environment means also the IDE must rebuild its classpath from the OSGi metadata. There are many hidden costs to the use of external libraries.

 See, you do not update something that works just because a newer version of a lib is out, last thing you want is an automated update, think about configuration management and quality assurance.

Using external libraries and managing them adds complexity, but offers flexibilty and control.

OSGi and Maven both manage dependencies (Maven at build time, OSGi at runtime), a change in the dependencies is a change to the SW itself, so it is completely natural to rebuild/repackage/redistribute the app.

Apart from that i doubt that it makes much sense to compare Java and PHP, even in the context of WebApps,  they are very different when it comes to the problems they solve.

As a Java developer since 10 years there is nothing i envy PHP for, sometimes i wished that is was simplier to hack up a quick & dirty prototype for the web, but that would come at the cost of having even more crappy WebApps and "Milli Vanilli" Java developers out there ;)

Balint Persics replied on Wed, 2011/01/26 - 10:57am in response to: Giorgio Sironi

That is also true for PHP libraries which you rely upon, like Zend Framework, Doctrine, fpdf, jpgraph and so on. They must be imported to version control, you must be careful with deployment etc. OSGi and IDE has nothing much in common. The OSGi metadata is only useful for the OSGi runtime, apart from that, those JAR files are simple plain old JARs.

Andy Leung replied on Wed, 2011/01/26 - 4:59pm in response to: Dewald Botha

Dewald, are you sure you want to build a banking site using PHP????!!! LOL....look, this is not Facebook kinda app so I wonder who will actually use PHP to make banking sites.

Dewald Botha replied on Thu, 2011/01/27 - 3:37am in response to: Andy Leung

Hi Andy - to be honest I have seen stranger things. 

Point being that it is not impossible to use PHP for that.  Historically Java would be the better choice, because of its power and proven track record.  The issue is that PHP has been boxed as a 'script kiddy' language. 

I have worked in C, Java, Ruby, Python and PHP and to be honest I can't see a reason for not using it.  The language has matured more in recent years and so has the developers using it.  If you use sound principles and get engineers that could implement it accordingly, why not?  Unless there is some horrible flaw in PHP which isn't present in other languages?


michael cheung replied on Thu, 2011/01/27 - 6:07pm

Has anyone try quercus? It allows you to run php code in java vm. I am stuck with php because of the decision made in the company. Coming from a java background, php lacks of a lot of things. It is a step backward for me. If anyone try quercus with spring mvc, please let me know your feedback. Thanks!

Gar Labs replied on Sun, 2011/10/23 - 11:06am

Another perspective that compares Java vs PHP is all we need. It is like what is the advantage over the other. Consumers must know these facts because these are crucial informations for them to decide. - GAR Labs

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.