Forum und email

PHP / Java Integration

소개

There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension.

The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process.

Warning

이 확장 모듈은 실험적입니다. 이 확장 모듈의 작동 -- 함수의 이름과 이 확장 모듈에 대한 모든 문서 자료에 대해서 -- 은 이후의 PHP 릴리즈에서 예고 없이 변경될 수 있습니다. 이 확장 모듈의 사용은 사용자의 책임하에 이루어집니다.

요구 조건

You need a Java VM installed on your machine to use this extension.

설치

» PECL 확장은 PHP 배포판에서 제공하지 않습니다.

PHP 4에서 이 PECL 확장의 소스는 PHP 소스의 ext/ 디렉토리 안이나, 위의 PECL 링크에서 찾을 수 있습니다. In order to use these functions you must compile PHP with Java support by using the --with-java[=DIR] where DIR points to the base install directory of your JDK. This extension can only be built as a shared extension. Additional build extensions can be found in php-src/ext/java/README.

Windows users will enable php_java.dll inside of php.ini in order to use these functions. PHP 4에서 이 DLL 형식은 내려받은 PHP 윈도우 바이너리 안의 extensions/ 디렉토리 안에 있습니다. PECL 확장 DLL» PHP 내려받기 페이지나 » https://pecl4win.php.net/에서 받을 수 있습니다.

Note: In order to enable this module on a Windows environment with PHP <= 4.0.6, you must make jvm.dll available to your systems PATH. No additional DLL is needed for PHP versions > 4.0.6.

실행시 설정

이 함수의 작동은 php.ini 설정에 영향을 받습니다.

Java configuration options
Name Default Changeable Changelog
java.class.path NULL PHP_INI_ALL  
java.home NULL PHP_INI_ALL  
java.library.path NULL PHP_INI_ALL  
java.library JAVALIB PHP_INI_ALL  
PHP_INI_* 상수에 대한 자세한 상세와 정의는 php.ini directives를 참고하십시오.

자원형

이 확장은 리소스형을 정의하지 않습니다.

예약 상수

이 확장은 상수를 정의하지 않습니다.

예제

Example#1 Java Example

<?php
// get instance of Java class java.lang.System in PHP
$system = new Java('java.lang.System');

// demonstrate property access
echo 'Java version=' $system->getProperty('java.version') . '<br />';
echo 
'Java vendor=' $system->getProperty('java.vendor') . '<br />';
echo 
'OS=' $system->getProperty('os.name') . ' ' .
             
$system->getProperty('os.version') . ' on ' .
             
$system->getProperty('os.arch') . ' <br />';

// java.util.Date example
$formatter = new Java('java.text.SimpleDateFormat',
                      
"EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz");

echo 
$formatter->format(new Java('java.util.Date'));
?>

Example#2 AWT Example

<?php
// This example is only intended to be run as a CGI.

$frame  = new Java('java.awt.Frame''PHP');
$button = new Java('java.awt.Button''Hello Java World!');

$frame->add('North'$button);
$frame->validate();
$frame->pack();
$frame->visible True;

$thread = new Java('java.lang.Thread');
$thread->sleep(10000);

$frame->dispose();
?>
Notes:
  • new Java() will create an instance of a class if a suitable constructor is available. If no parameters are passed and the default constructor is useful as it provides access to classes like java.lang.System which expose most of their functionallity through static methods.
  • Accessing a member of an instance will first look for bean properties then public fields. In other words, print $date.time will first attempt to be resolved as $date.getTime(), then as $date.time.
  • Both static and instance members can be accessed on an object with the same syntax. Furthermore, if the java object is of type java.lang.Class, then static members of the class (fields and methods) can be accessed.
  • Exceptions raised result in PHP warnings, and NULL results. The warnings may be eliminated by prefixing the method call with an "@" sign. The following APIs may be used to retrieve and reset the last error:

  • Overload resolution is in general a hard problem given the differences in types between the two languages. The PHP Java extension employs a simple, but fairly effective, metric for determining which overload is the best match. Additionally, method names in PHP are not case sensitive, potentially increasing the number of overloads to select from. Once a method is selected, the parameters are coerced if necessary, possibly with a loss of data (example: double precision floating point numbers will be converted to boolean).
  • In the tradition of PHP, arrays and hashtables may pretty much be used interchangably. Note that hashtables in PHP may only be indexed by integers or strings; and that arrays of primitive types in Java can not be sparse. Also note that these constructs are passed by value, so may be expensive in terms of memory and time.

Java Servlet SAPI

The Java Servlet SAPI builds upon the mechanism defined by the Java extension to enable the entire PHP processor to be run as a servlet. The primary advantage of this from a PHP perspective is that web servers which support servlets typically take great care in pooling and reusing JVMs. Build instructions for the Servlet SAPI module can be found in php4/sapi/README. Notes:

  • While this code is intended to be able to run on any servlet engine, it has only been tested on Apache's Jakarta/tomcat to date. Bug reports, success stories and/or patches required to get this code to run on other engines would be appreciated.
  • PHP has a habit of changing the working directory. sapi/servlet will eventually change it back, but while PHP is running the servlet engine may not be able to load any classes from the CLASSPATH which are specified using a relative directory syntax, or find the work directory used for administration and JSP compilation tasks.

Table of Contents