Your own classes

The next step forward is to use Java to create your own classes, compile that using javac, then load the class into PHP for use. This is better than feeding Java code in line by line because you can put a lot of your application logic into the Java class, which is then properly compiled down into byte code. You can then simply call just one function from your PHP script to do a lot of Java processing.

Consider the following Java code, factor.java, which calculates the factorial of a number:

public class factor {
    public int factor(int num) {
        if ((num == 0) || (num == 1)) return 1;
        return num * factor(num - 1);
    }
}

We looked at calculating factorials many chapters ago, so I shan't explain again what they are. This time around there is the slight optimisation that we also do not bother recursing the function if the number to calculate is 1.

Once that file is compiled, we will have factor.class, our own Java class file. This should be copied to the location you entered into your php.ini file as your class path, thereby making the class file available for us to use in PHP. When creating a new Java object, Java will search for the class file for that object in several places, the last of which is the directory specified by your php.ini file. As a result, we can create an object of this class with the following code:

$myfactor = new Java('factor');

As you can see, the main class is called "factor", so that is what we use to create the object. The main (and only!) function is also called factor, and takes an integer parameter to calculate. Therefore, here is the complete PHP script to calculate factors using the Java factor class we created:

<?php
    $factor = new Java('factor');
    print $factor->factor(4);
?>

As you can see there are no big surprises here - the factor() function of our factor object is called, passing in 4. This should return 24, because 4 x 3 x 2 x 1 is 24. Note that if you want to use large values with this, you should modify the Java class to return a double-precision floating-point number, because integers do not go very high.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Using Swing >>

Previous chapter: The drawbacks of basic Java use

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.