PHP DevCenter

oreilly.comSafari Books Online.Conferences.

We've expanded our LAMP news coverage and improved our search! Search for all things LAMP across O'Reilly!

Search
Search Tips

advertisement

Listen Print Subscribe to PHP Subscribe to Newsletters

PHP and Java
Pages: 1, 2

Using custom libraries

Of course, chances are you will want to implement custom-written classes within your applications, rather than relying solely on those packages provided by the Java distribution. To illustrate how these third-party classes are used within a PHP application, I'll create a simple Java class that calculates sales tax based upon a price and taxation rate input by the user, shown in Listing 2. You'll need to compile salesTax.java using the Java compiler before you can use this class within the PHP script shown in Listing 3. I'll show you how this is accomplished in a bit. For the moment, just take some time to review Listing 2.



Listing 2: salesTax.java

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;

    }

}

Once you've saved this code within a file named salesTax.java, you'll need to compile it. This is accomplished by executing the following command:

%>javac salesTax.java

Assuming that you haven't introduced any errors into the code, a new, compiled file named salesTax.class will be created. This is the compiled code that will be called by PHP to perform the calculation based on the data input by the user via an HTML form. This form, along with the PHP code that calls salesTax.class, is shown in Listing 3 (salesTaxInterface.php).

Listing 3: salesTaxInterface.php

<?php

// Format the HTML form.
$salesTaxForm = <<<SalesTaxForm
   <form action="SalesTaxInterface.php" method="post">
   Price (ex. 42.56):<br>
   <input type="text" name="price" size="15" maxlength="15" value=""><br>
   Sales Tax rate (ex. 0.06):<br>
   <input type="text" name="tax" size="15" maxlength="15" value=""><br>
   <input type="submit" name="submit" value="Calculate!">
   </form>
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;

?>

Troubleshooting

Chances are you will encounter various minor problems when you first attempt to integrate Java and PHP functionality, particularly if you are a relative newcomer to the Java programming environment. Even if the Java code compiles correctly, you may still encounter problems, largely due to differences found between the two languages. I'll outline two of these differences here:

Data types

As you may know, PHP is a loosely-typed language, which means it is rather lenient on the way variables are used. On the contrary, Java is a strongly-typed language, which means that its policies for handling variables and data types are rather stringent. To illustrate the problem this difference poses, take a moment to again review the code found in Listing 3. Notice that I had to typecast the $price and $tax variables before passing them to the SalesTax() method, because this method requires that both input parameters are of type "double." If this is not done, then input such as 24 for price would cause an error to occur.

Furthermore, if you are not adamant in ensuring the correct data types are passed to the Java methods, you may receive unexpected results, although it will not be outwardly apparent that an error has occurred. Therefore, be careful!

Error reporting

Errors occurring within a PHP script are reported in accordance with the level of error-reporting specified in the php.ini file. Because the Java code is called from within the PHP script, any errors that arise from the Java code are displayed as PHP errors. If you would like to prevent these errors from being displayed to the browser, simply prefix a @ symbol to the PHP command.

Conclusion

This article introduced you to what is in my opinion one of PHP's coolest new features, the Java extension. Using this extension opens up a whole new realm of possibilities for enhancing your existing applications, some of which I introduced in this article. Furthermore, I discussed several problems which may arise as a result of integrating these two languages, both on a general configuration level and on the level of inconsistencies between the languages.

Next time, I'll introduce another new and interesting extension, Shockwave. You'll be shocked at the cool presentations you can make with just a few lines of PHP code.

W.J. Gilmore has been developing PHP applications since 1997, and is frequently published on the subject within some of the Web's most popular development sites. He is the author of 'A Programmer's Introduction to PHP 4.0' (January 2001, Apress), and is the Assistant Editorial Director of Web and Open Source Technologies at Apress.


Return to the PHP DevCenter.




Tagged Articles

Post to del.icio.us

This article has been tagged:

programming

Articles that share the tag programming:

Rolling with Ruby on Rails (1374 tags)

Very Dynamic Web Interfaces (279 tags)

Ajax on Rails (231 tags)

Understanding MVC in PHP (202 tags)

A Simpler Ajax Path (186 tags)

View All

java

Articles that share the tag java:

Profiling Your Applications with Eclipse Callisto (113 tags)

What Is a Portlet (101 tags)

Parsing an XML Document with XPath (79 tags)

The REST of the Web (75 tags)

Eclipse Plugins Exposed, Part 1: A First Glimpse (69 tags)

View All

php

Articles that share the tag php:

Understanding MVC in PHP (477 tags)

The PHP Scalability Myth (123 tags)

The Dynamic Duo of PEAR::DB and Smarty (53 tags)

PHP Form Handling (43 tags)

Very Dynamic Web Interfaces (39 tags)

View All

Sponsored Resources

  • Inside Lightroom
Advertisement

Sponsored by:

O'Reilly Media

©2009, O'Reilly Media, Inc.
(707) 827-7000 / (800) 998-9938
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
About O'Reilly
Academic Solutions
Authors
Contacts
Customer Service
Jobs
Newsletters
O'Reilly Labs
Press Room
Privacy Policy
RSS Feeds
Terms of Service
User Groups
Writing for O'Reilly
Content Archive
Business Technology
Computer Technology
Google
Microsoft
Mobile
Network
Operating System
Digital Photography
Programming
Software
Web
Web Design
More O'Reilly Sites
O'Reilly Radar
Ignite
Tools of Change for Publishing
Digital Media
Inside iPhone
O'Reilly FYI
makezine.com
craftzine.com
hackszine.com
perl.com
xml.com

Partner Sites
InsideRIA
java.net
O'Reilly Insights on Forbes.com