How to Convert From Java to PHP

Techwalla may earn compensation through affiliate links in this story. Learn more about our affiliate and product review process here.
Java integrates well with PHP.

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.

Advertisement

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:

Video of the Day

import java.util.; import java.text.;

public class SalesTax {

Advertisement

public String SalesTax(double price, double salesTax) {

numberFormatter.format(salesTax);

}

Advertisement

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:

<?php

// Format the HTML form.

Advertisement

$salesTaxForm = <<<SalesTaxForm

Price (ex. 42.56):


Advertisement

Advertisement

Sales Tax rate (ex. 0.06):


Advertisement

SalesTaxForm;

if (! isset($submit)) :

echo $salesTaxForm;

else :

Advertisement

// Instantiate the SalesTax class. $salesTax = new Java("SalesTax");

// Don't forget to typecast in order to

// conform with the Java method specifications.

Advertisement

$price = (double) $price; $tax = (double) $tax;

Advertisement

print $salesTax->SalesTax($price, $tax);

endif;

Advertisement

?>

Step 3

Add the following code to your project to bridge Java and PHP together:

#!/bin/env php <?php

Advertisement

require_once("java/Java.inc");

include("wsimport.php");

try { $addNumbersService = new java("org.duke.AddNumbersService"); $port = $addNumbersService->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"); } } ?>

Video of the Day

Advertisement

Advertisement

references & resources