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.
Now, the example on the previous page used a built-in Java class to demonstrate PHP/Java connectivity. It's also possible to instantiate and use a custom Java class in a PHP script. I'll demonstrate this by encapsulating the functionality of the core File class in my own FileReader class.
Here's the code for my custom class:
public class FileReader
public File LocalFile;
// set file location
public void loadFile(String FileName)
LocalFile = new File(FileName);
// return file size
public long getFileSize()
// check if file exists
public boolean FileExists()
// return file path
public String getFilePath()
There's no rocket science here - this class is only a wrapper
for core File class methods. However, it will serve to demonstrate the basics of using a custom Java class in a PHP script.
Now, compile the class, copy the compiled code to your Java CLASSPATH, and write a script to use it.
$myClass = new Java("FileReader");
echo "File size is " . $myClass->getFileSize() . "<br>";
echo "File path is " . $myClass->getFilePath();
echo "Sorry, the file " . $myClass->getFilePath() . " could not
be found"; }
This is similar to the first example, except that, this time,
I've used my own custom Java class in the script. Once an instance of the class has been instantiated, class methods can be accessed in the normal manner.