XLVII. 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.

警告

這個延伸是 實驗性質的。這個延伸的行為 -- 包括函數名稱和包含此延伸的任何其它文件 -- 在未來PHP的發行中可能會在不通知的情況改變。使用此延伸需自行承擔風險。

執行時期組態

php.ini中的設定會影響這些函數的行為。

表格 1. Java configuration options

Name Default Changeable
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
For further details and definition of the PHP_INI_* constants see ini_set().

範例

範例 1. Java Example

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

  // demonstrate property access
  print 'Java version='.$system- getProperty('java.version').'  br ';
  print 'Java vendor=' .$system- getProperty('java.vendor').'  br ';
  print '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");

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

範例 2. AWT Example

 ?php
  // This example is only intented 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:


內容目錄
java_last_exception_clear -- Clear last Java exception
java_last_exception_get -- Get last Java exception