You probably already know that PHP comes with extensions for awide variety of different technologies. But did you know that you couldhook PHP up to Java, and use Java classes and Java Beans from withinyour PHP scripts? If this is news to you, keep reading.
Let's begin with a simple example to verify that everything is working as advertised. This script uses built-in Java methods to check for the existence of a particular file on your system and display its size.
<?php
$fp = new Java("java.io.File", "/home/john/test.txt");
if($fp->exists())
{
echo "The file ". $fp->getAbsolutePath() . " is ". $fp->length()
. " bytes"; }
else
{
echo "The file " . $fp->getAbsolutePath() . " does not exist"; }
?>
This is fairly simple, and should be clearly understandable
to anyone who knows basic Java programming. The first line of the script instantiates an object of Java's File class, and stores it in the PHP variable $fp.
$fp = new Java("java.io.File", "/home/john/test.txt");
In case you're wondering, it's possible to pass parameters to
the class constructor by specifying them as arguments when creating the object. In the example above, the second argument to the class constructor contains the location of the file to be displayed.
Once the object has been instantiated, it becomes possible to access the methods and properties of the Java class using regular OOP syntax.
if($fp->exists())
{
echo "The file ". $fp->getAbsolutePath() . " is ". $fp->length()
. " bytes"; }
else
{
echo "The file " . $fp->getAbsolutePath() . " does not exist"; }
In this case, the exists(), getAbsolutePath() and length()
methods are all methods of the File class; however, I've managed to use them in a PHP script by virtue of the Java connectivity built into PHP.
Here's what the output of the script above looks like: