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_
Aviso
Esta extensión es
EXPERIMENTAL_ Esto significa que el
comportamiento de esta extensión, los nombre de sus funciones y
en definitiva TODO lo documentado sobre esta extensión, puede
cambiar en una futura versión de PHP SIN AVISO_ La advertencia
queda hecha, y utilizar esta extensión queda bajo su propia
responsabiliad_
Requerimientos
You need a Java VM installed on your machine to use this extension_
Instalación
Para incluir el soporte de Java en PHP, es necesario añadir el
parámetro __with_java[=DIR] a las opciones de configuración de PHP_ Ademas, es necesario indicarle a traves de la opción DIR, el lugar donde se encuentra el directorio base de la instalación del JDK_ Esta extensión solamente puede ser construida como un modulo compartido_ En el archivo php4/ext/java/README se incluye mas información sobre como construir esta extensión_
Nota para los usuarios de Windows:
Para poder trabajar con este modulo en un entorno Windows con una versión de PHP <= 4_0_6,
se debe copiar el archivo jvm_dll que se encuentra en el subdirectorio DLL del directorio PHP/Win32 de la distribución binaria de PHP, en el directorio SYSTEM32 de Windows (Normalmente es C:\WINNT\SYSTEM32 o C:\WINDOWS\SYSTEM32)_ Para versiones de PHP > 4_0_6 no es necesario realizar esta operación_
Configuración en tiempo de
ejecución
El comportamiento de estas
funciones está afectado por los valores definidos en
php_ini_
Tabla 1_ Opciones de configuraci??? de Java
Nombre
Valor por defecto
Donde se cambia
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
Para conocer todos los detalles y las definiciones de las constantes de PHP_INI_* se debe consultar la función ini_set()_
Tipos de recursos
Esta extensión no tiene
ningún tipo de recurso definido_
Constantes predefinidas
Esta extensión no tiene ninguna
constante definida_
Ejemplos
Ejemplo 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'));
?>
Ejemplo 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 cooerced 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 advanatage 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_