Using PHP with Java - Passing The Parcel (
Page 5 of 7 )
This next example demonstrates how one object instance
can be passed to another in a single PHP script.
Here's the code:
import java.io.Writer;
import java.io.IOException;
import java.lang.Exception;
public class ReverseString
{
public Writer out;
public void setWriter(Writer out)
{
this.out = out;
}
public void reverse(String string) throws Exception
{
try
{
// reverse the string here
char tempArray[] = new char[string.length()];
for (int i = 0; i < string.length(); i++)
tempArray[i] =
string.charAt(string.length() - i - 1);
String reversedString = new String(tempArray);
out.write(reversedString);
}
catch (IOException e)
{
// catch IO exceptions
throw new Exception("Something bad
happened");
}
catch (Exception e)
{
// catch everything else
throw new Exception("Something really
bad happened");
}
}
}
This class uses a Writer object for script communication;
this Writer object is instantiated via the setWriter() class method.
public void setWriter(Writer out)
{
this.out = out;
}
Next, the class method reverse() accepts a string, reverses
it and returns it via the Writer object.
public void reverse(String string) throws Exception
{
try
{
// reverse the string here
char tempArray[] = new char[string.length()];
for (int i = 0; i < string.length(); i++)
tempArray[i] =
string.charAt(string.length() - i - 1);
String reversedString = new String(tempArray);
out.write(reversedString);
// snip
}
}
Compile this class, copy it to your Java CLASSPATH, and write
a simple PHP script to access it.
<?php
// create an instance of the ReverseString object
$obj = new Java("ReverseString");
// create an instance of the StringWriter object
$writer = new Java("java.io.StringWriter");
$obj->setWriter($writer);
$obj->reverse("The cow jumped over the moon");
echo $writer->toString();
$writer->flush();
$writer->close();
?>
In this case, I've instantiated two objects, one for the
ReverseString class and the other for the StringWriter class. Next, I've passed
the StringWriter object, as stored in the PHP object $writer, to the
ReverseString class via the class' setWriter() method, and then used the
reverse() method to reverse a string and return the result.
Here's what
the output looks like:
noom eht revo depmuj woc ehT