| |
|
 |
Interfacing with Java from PHP
|
The magic
I've decided not to use templates in the .php file due to simplicity. If you want to know more about how to separate the html tags from the PHP code you can read the article about block templates here
The contents of the PHP file is shown at the end of the article as a whole. Study this code and I will try to explain the basic behavior of the code.
First off I want to mention the fact that you can instantiate Java classes and use them as PHP objects directly in the PHP code. The code snippet below shows how you can instantiate the eZCalc class into a PHP object called $calc. You can call member functions on the $calc object directly, as shown in the example. Note that you should manually set the type of the PHP variables sent as arguments to the Java objects. This is due to the large difference in types between PHP and Java. The example below demonstrates how you set the values used for calculation in the Java object.
// create a new java object, $calc
$calc = new Java( "eZCalc" );
// force the type to be compatible with Java types
setType( $number1, "double" );
setType( $number2, "double" );
$calc->setA( $number1 );
$calc->setB( $number2 ); |
Now lets see how the calculation works. First off we have four calculation types in our calculator; add, sub, mul and div. We switch on the different types and call up the $calc object with the correct calculation type, e.g. $result = $calc->subtract();. Here the Java object returns the value calculated inside the Java object.
In this example I have only used simple types to communicate between Java and PHP. You can also exchange arrays between Java and PHP. Objects cannot be exchanged between PHP and Java.
$operator = "";
switch( $calctype )
{
case( "add" ):
$result = $calc->add();
$operator = "+";
break;
case( "sub" ):
$result = $calc->subtract();
$operator = "-";
break;
case( "mul" ):
$result = $calc->multiply();
$operator = "*";
break;
case( "div" ):
$result = $calc->divide();
$operator = "/";
break;
} |
Comment List
There are no comments.
|
 |
|
|