How to Convert From Java to PHP

By Joey Liam

Java and PHP are two of the most used programming languages today. Although both technologies offer advanced functionality and dynamic portability, converting one to the other is not quite possible yet. The good news though is that Java and PHP classes can be integrated together to form efficient applications, such as for sales tax calculation. The main script to be used for this PHP-Java integration project is PHP script and the compiler will be Java.

Step 1

Paste the code below to establish your Java compiler, which you will need to compile your salesTax.java project within the PHP script:import java.util.*;import java.text.*;public class SalesTax {public String SalesTax(double price, double salesTax) { double tax = price * salesTax; NumberFormat numberFormatter; numberFormatter = NumberFormat.getCurrencyInstance(); String priceOut = numberFormatter.format(price); String taxOut = numberFormatter.format(tax); numberFormatter = NumberFormat.getPercentInstance(); String salesTaxOut = numberFormatter.format(salesTax); String str = "A sales Tax of " + salesTaxOut + " on " + priceOut + " equals " + taxOut + "."; return str; }}

Step 2

Run PHP to call the compiled code called SalesTaxInterface.php. This function will calculate the data inputted by the user in your HTML form: Price (ex. 42.56): Sales Tax rate (ex. 0.06): SalesTaxForm;if (! isset($submit)) : echo $salesTaxForm;else : // Instantiate the SalesTax class. $salesTax = new Java("SalesTax"); // Don't forget to typecast in order to // conform with the Java method specifications. $price = (double) $price; $tax = (double) $tax; print $salesTax->SalesTax($price, $tax);endif;?>

Step 3

Add the following code to your project to bridge Java and PHP together:#!/bin/env php getAddNumbersPort(); $number1 = 10; $number2 = 20; echo ("Invoking one-way operation. Nothing is returned from service.\n"); $port->oneWayInt($number1); echo ("Invoking addNumbers($number1, $number2)\n"); $result = $port->addNumbers($number1, $number2); echo ("The result of adding $number1 and $number2 is $result\n\n"); $number1 = -10; echo ("Invoking addNumbers($number1, $number2)\n"); $result = $port->addNumbers($number1, $number2); echo ("The result of adding $number1 and $number2 is $result\n\n"); } catch (JavaException $ex) { $ex = $ex->getCause(); if (java_instanceof($ex, java("org.duke.AddNumbersFault_Exception"))) { $info = $ex->getFaultInfo()->getFaultInfo (); echo ("Caught AddNumbersFault_Exception: $ex, INFO: $info.\n"); } else { echo ("Exception occured: $ex\n"); } } ?>

Tips & Warnings

  • There are hundreds of free tutorials for Java and PHP to learn from, so study as many as you can to gain a basic understanding about how these programming languages work. Also, learn from experienced users by seeking their guidance and advice in discussion forums.