Basic Java use

As with COM, Java objects are encapsulated with a single class, "Java". This takes the name of the Java object to create as its constructor parameter, and returns the object. This is best illustrated with a very simple example, so here you go:

<?php
    $java = new Java('java.lang.System');
    $version = $java->getproperty('java.version');
    print "Hello from Java $version!\n";
?>

Line one creates a new Java object of type java.lang.System. If you have used Java before, you will know that java.lang.System is a core class that offers some of the most basic functionality in Java. That line of code creates an instance of java.lang.System, and stores it in the $java PHP variable, upon which we can call functions, read variables, etc.

Line two demonstrates calling a function on the Java object, getProperty(). The getProperty() function is documented (at the time of writing) at http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#getProperty(java.lang.String), and takes the string parameter of the property you want to read.

It is important to note that in Java, this function is called getProperty(), but thanks to PHP not having case-sensitive function names, you can use getproperty(). This might cause some confusion in poorly written classes where overloaded function calls are decided based upon capitalisation of the function names, but otherwise PHP does a good job of picking out which overloaded function to use, if any.

It is also important to note that Java is a strongly typed language, whereas PHP is weakly typed. Strictly speaking, getProperty() takes a string as its parameter, whereas PHP does not distinguish between strings, integers, and so on. However, when interacting with Java, PHP will decide which function you want to call, then automatically convert the parameters you pass in so that they match what the Java function expects. If you encounter problems with this, you might want to try explicitly typecasting your PHP variables before using them in a function call.

Our getProperty() call will return the specified value, in this case the version number of the JVM that is being used. This is captured in the $version variable, then printed out to the screen - simple, really.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: The drawbacks of basic Java use >>

Previous chapter: Bringing Java into the mix

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.