And now instead, 5 things Java envies PHP for
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) {
System.out.println(dis.readLine());
}
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}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);
doc.getDocumentElement().normalize();
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) {
e.printStackTrace();
}compare with:
<?php
$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.






Comments
Balint Persics replied on Tue, 2011/01/25 - 8:54am
Wojciech Kudla replied on Tue, 2011/01/25 - 8:57am
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.
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
Yaman Asdasd replied on Tue, 2011/01/25 - 9:35am
Jason Mulligan replied on Tue, 2011/01/25 - 10:12am
Balint Persics replied on Tue, 2011/01/25 - 10:25am
in response to:
Yaman Asdasd
Balint Persics replied on Tue, 2011/01/25 - 10:30am
in response to:
Jason Mulligan
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()) { System.out.println(scanner.nextLine()); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if(scanner != null) { scanner.close(); } }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++) { System.out.println(nodeList.item(i).getTextContent()); }Giorgio Sironi replied on Tue, 2011/01/25 - 1:42pm
in response to:
Balint Persics
Giorgio Sironi replied on Tue, 2011/01/25 - 1:43pm
in response to:
Andrea Del Bene
Giorgio Sironi replied on Tue, 2011/01/25 - 1:43pm
in response to:
Andrea Del Bene
Giorgio Sironi replied on Tue, 2011/01/25 - 1:50pm
in response to:
Yaman Asdasd
Jonathan Fisher replied on Tue, 2011/01/25 - 2:14pm
Balint Persics replied on Tue, 2011/01/25 - 2:18pm
in response to:
Giorgio Sironi
Christian Schli... replied on Tue, 2011/01/25 - 3:37pm
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 { reader.close(); }That's it.
Cloves Almeida replied on Tue, 2011/01/25 - 10:25pm
Batteries not included?
Well,
1) wget -P lib http://jdbc.postgresql.org/download/postgresql-9.0-801.jdbc4.jar
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.
exit(1);
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
Mladen Girazovski replied on Wed, 2011/01/26 - 8:38am
in response to:
Giorgio Sironi
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
Andy Leung replied on Wed, 2011/01/26 - 4:59pm
in response to:
Dewald Botha
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
Gar Labs replied on Sun, 2011/10/23 - 11:06am