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:
import java.io.*;
public class FileReader
{
public File LocalFile;
// set file location
public void loadFile(String FileName)
{
LocalFile = new File(FileName);
}
// return file size
public long getFileSize()
{
return LocalFile.length();
}
// check if file exists
public boolean FileExists()
{
return LocalFile.exists();
}
// return file path
public String getFilePath()
{
return LocalFile.getAbsolutePath();
}
}
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.
<?php
$myClass = new Java("FileReader");
$myClass->loadFile("/home/john/test.txt");
if($myClass->FileExists())
{
echo "File size is " . $myClass->getFileSize() . "<br>";
echo "File path is " . $myClass->getFilePath();
}
else
{
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.