There are at least 4 other php to java bridges which offer a similar API. One was distributed with PHP 4.0.0 and has been discontinued. Two other bridges are proprietary software, built into a vendor-specific framework from Zend or a J2EE application server from Caucho. Furthermore IBM's Zero framework for Eclipse contains a PHP interpreter written in pure Java and a php to java bridge which can call Java methods in-process.
The only free alternatives are SOAP and XML-RPC, which are up to 50 times slower than the XML protocol implementation used by this VM Bridge.
A Java extension does not exist, so you can't enable it.
The VM Bridge is a network protocol, it requires a running Java VM, for example the servlet container Apache/Tomcat. Or, if you want to call PHP libraries from Java, a running PHP container, e.g. Apache or IIS.
Only the PHP code from Java.inc
and a running Java application, for example JavaBridge.jar
, or a running Java servlet, for example JavaBridge.war
.
Only the PHP code from JavaProxy.php
within your PHP web application and the Java libraries JavaBridge.jar
, php-script.jar
and php-servlet.jar
.
RequestListener
declaration from the WEB-INF/web.xml.Java needs an execution environment.
You can also add PHP support to your standalone Java application by adding the following line to its main class:
static final php.java.bridge.JavaBridgeRunner runner = php.java.bridge.JavaBridgeRunner.getInstance(8087);
The above code opens the port 8087, so that local PHP scripts can call
methods/procedures from your Java application, as long as your Java
application is running.
The third option is the standard JSR 223 script interface, which allows one to execute PHP code/scripts from Java applications.
Copy log4j.jar
into java.ext.dirs
. Example for JDK 6:
cp log4j.jar /usr/java/packages/lib/ext
Start the log4j viewer. Example for JDK 6:
/opt/jdk1.6/bin/java org.apache.log4j.chainsaw.Main
Start the application server with the options -Dphp.java.bridge.default_log_level=LEVEL
. Example for tomcat:
JAVA_HOME=/opt/jdk1.6 JAVA_OPTS="-Dphp.java.bridge.default_log_level=5" bin/catalina.sh run
Example for the standalone container:
java -Dphp.java.bridge.default_log_level=5 -jar JavaBridge.jar SERVLET:8080
With the -D flag. See java -jar JavaBridge.jar --help for details. If tomcat is being used, one can set these options as follows:
JAVA_OPTS="-D... -D..." /opt/tomcat/bin/catalina.sh run
Use a VM >= 1.6 and add more RAM to your computer. Older Java versions
support the Xmx
flag:
java -Xmx512M ... -jar JavaBridge.jar SERVLET:8080
With a define
before a PHP library is loaded. Global options can also be set in the php.ini
file. Use phpinfo() to see the location of this file.
Useful options which can be set before the Java.inc/Mono.inc is loaded are:
define ("JAVA_DEBUG", false);
define ("JAVA_PREFER_VALUES", false);
define ("JAVA_HOSTS", "127.0.0.1:8080");
define ("JAVA_PIPE_DIR", null);
require_once ("java/Java.inc");
...
Please see the Options.inc for details.
Server-side options can be set in the php.java.bridge.global.properties file, see the JavaBridge.jar zip file (contained in the JavaBridge.war zip file) for details.
Yes. On a GNU operating system (e.g.: GNU/Linux, GNU/windows (aka "cygwin"), ...) you can use the GCC compiler to compile Java classes to native code.
Simply compile the C based extension and omit the
--with-java=
configure option. The bridge will use the
libgcj
library, which is part of the GNU gcc compiler. This library also uses much less system
resources (memory, files) than a "real" Java VM.
The "current working directory" is not useful, as the Java back end may be running on a different server or from a different working directory. Use a full path or a URL resource instead.
Check the PHP error log, see your php.ini
file for details. If the command:
echo '<?php require_once("http://localhost:8080/JavaBridge/java/Java.inc"); echo java("java.lang.System")->getProperties();?>' | php -n -d allow_url_include=On
works in the shell but not within apache, then there's something wrong with your php.ini
file.
Yes, see the examples folder from the source download.
Yes, there's a PHP library "Mono.inc" generated from "Java.inc" and
a "MonoBridge.exe" generated from "JavaBridge.jar". If you want to
compile from source, use the configure
option --with-mono
.
That your Java or .NET VM has problems, for example an OutOfMemoryError. Check the back end (Tomcat/J2EE/.NET/...) log for details.
No. Use VM Bridge version 4.3.2 or below instead.
During development simple libraries can be loaded dynamically with java_require("myApplication.jar;myLib1.jar;myDriver1.jar;...");
. See the README for details.
Either within your web application WEB-INF/lib
directory or in php.java.bridge.base
/lib.
When the system property php.java.bridge.base
is not set, libraries are loaded from $HOME/lib
where $HOME
denotes the home directory of the person or component which has started the java VM.
If libraries should be available globally, store them in java.ext.dirs
, for example in /usr/share/java/ext
.
If a library is not yet API-stable, store it into a sub directory of the lib
directory and use the java_require()
procedure. For example java_require("myLibs0.2/foo.jar")
loads foo.jar
from php.java.bridge.base/lib/myLibs0.2
.
It probably doesn't have the permission to access it. Check if baz.jar is a valid Java archive and if its main class is public. Try to disable Security Enhanced Linux and store the jar file into a folder accessible by the apache user and then extract the required Security Enhanced Linux permissions from the audit log.
You probably haven't required the relevant Java library. Or the
class doesn't exist or it is not public or it throws a java.lang.Error
during initialization. Check which library exports the feature and add
the library to the java_require()
statement.
Because Java doesn't have a module system.
All libraries and their dependencies must be loaded by one, and only one class loader.
Please read the previous sentence until you understand what it means; for example a simple file system copy(!) operation may be the cause for a NoClassDefFoundError.
Please do not report NoClassDefFoundErrors to the mailing list or via the bug tracker. This is not a bug and we cannot help you any further!
Please re-read the class loading section. The following code loads all interconnected libraries using a single java_require() call:
java_require("myApplication.jar;myJdbcDriver.jar");
...
$myApplication->callWithMyJdbcDriver();
The following incorrect code fails because the application (the "JavaBridge.jar" in this case) cannot be accessed by the jdbc driver. This constraint is checked by the DriverManager:
java_require("myJdbcDriver.jar"); // WRONG!
new java("my.jdbc.Driver");
java("java.sql.DriverManager")->getDriver("myJdbcURL"); // FAILS!
If you really need to access the driver directly from PHP code, either use the driver API directly or load "JavaBridge.jar" and "myJdbcDriver.jar" from the same class loader so that the DriverManager can link them together. Use the extra library directory (usually ~/lib/
) or the global repository (usually /usr/java/packages/lib/ext
).
You can't. Java libraries must be pure Java.
Please read the
documentation of your J2EE server, Servlet engine or Java VM to see if and
how the environment can handle impure Java libraries. A common approach is to store the Java part in java.ext.dirs
and the native part in java.library.path
.
Set up the VM Bridge cluster as described below. The example uses two nodes named "carlos" and "diego". The HTTP server front end runs on the web server "timon".
Install Apache 2.2.0 or higher.
Enable proxy_module
and proxy_balancer_module
. The following example is for Linux (lines marked with "+" should be added to the conf/httpd.conf
file):
LoadModule rewrite_module modules/mod_rewrite.so
+ LoadModule proxy_module modules/mod_proxy.so
+ LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule cache_module modules/mod_cache.so
Add the following code to the bottom of your conf/httpd.conf
file:
ProxyPass /JavaBridge balancer://mycluster maxattempts=2
<Proxy balancer://mycluster>
BalancerMember http://diego:8080/JavaBridge
BalancerMember http://carlos:8080/JavaBridge
</Proxy>
<Location /balancer-manager>
SetHandler balancer-manager
Deny from all
Allow from 127.0.0.1
</Location>
Start the cluster nodes on "carlos" and "diego".
Browse to http://timon/JavaBridge/
(note the trailing slash) and click on the test.php. Click on refresh. Check if both nodes respond.
Browse to http://timon/JavaBridge/sessionSharing.php
and click on refresh. Check the cookie value.
Browse to http://timon/balancer-manager/
.
Please see the mod_rewrite
documentation for more information how to rewrite incoming URLs.
Download tomcat 5 or higher, a Java JRE 5 or higher and the VM Bridge 4.1.6 or higher.
The following example uses two nodes running on two machines called "carlos" and "diego".
On all nodes: Extract the tomcat distribution into a directory.
On "diego" add the following to conf/server.xml
:
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
channelSendOptions="8">
<Manager className="org.apache.catalina.ha.session.DeltaManager"
expireSessionsOnShutdown="false"
notifyListenersOnReplication="true"/>
<Channel className="org.apache.catalina.tribes.group.GroupChannel">
<Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
address="diego"
port="4000"
autoBind="100"
selectorTimeout="5000"
maxThreads="6"/>
</Channel>
</Cluster>
On "carlos" add the following to conf/server.xml
:
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
channelSendOptions="8">
<Manager className="org.apache.catalina.ha.session.DeltaManager"
expireSessionsOnShutdown="false"
notifyListenersOnReplication="true"/>
<Channel className="org.apache.catalina.tribes.group.GroupChannel">
<Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
address="carlos"
port="4000"
autoBind="100"
selectorTimeout="5000"
maxThreads="6"/>
</Channel>
</Cluster>
Copy the "JavaBridge.war" into the "webapps" directory on "diego" and "carlos" and start both nodes. For example with the command:
JAVA_OPTS="-Dphp.java.bridge.promiscuous=true" JAVA_HOME=/usr/java/default bin/catalina.sh run
Please see your HTTP server documentation and the description above how to set it up as a load balancer.
JavaBridge.war
into the tomcat webapps
folder.
JAVA_HOME=/usr/java/default /opt/tomcat/bin/catalina.sh run
mv /opt/tomcat/webapps/JavaBridge/WEB-INF/lib/* /opt/tomcat/lib
rm /opt/tomcat/webapps/JavaBridge/WEB-INF/web.xml
+
to the tomcat conf/web.xml
:
<!-- ================== Built In Servlet Definitions ==================== -->
+ <!-- PHP Servlet -->
+ <listener> <listener-class>php.java.servlet.ContextLoaderListener</listener-class> </listener>
+ <listener> <listener-class>php.java.servlet.RequestListener</listener-class> </listener>
+ <servlet>
+ <servlet-name>GlobalPhpJavaServlet</servlet-name>
+ <servlet-class>php.java.servlet.PhpJavaServlet</servlet-class>
+ </servlet>
+ <!-- PHP CGI Servlet -->
+ <servlet>
+ <servlet-name>GlobalPhpCGIServlet</servlet-name>
+ <servlet-class>php.java.servlet.PhpCGIServlet</servlet-class>
+ <init-param> <param-name>shared_fast_cgi_pool</param-name><param-value>On</param-value></init-param>
+ <init-param> <param-name>prefer_system_php_exec</param-name><param-value>On</param-value></init-param>
+ </servlet>
<!-- The default servlet for all web applications, that serves static -->
<!-- resources. It processes all requests that are not mapped to other -->
[...]
<!-- ================ Built In Servlet Mappings ========================= -->
+ <!-- PHP Servlet Mapping -->
+ <servlet-mapping>
+ <servlet-name>GlobalPhpJavaServlet</servlet-name>
+ <url-pattern>*.phpjavabridge</url-pattern>
+ </servlet-mapping>
+ <!-- CGI Servlet Mapping -->
+ <servlet-mapping>
+ <servlet-name>GlobalPhpCGIServlet</servlet-name>
+ <url-pattern>*.php</url-pattern>
+ </servlet-mapping>
<!-- The servlet mappings for the built in servlets defined above. Note -->
<!-- that, by default, the CGI and SSI servlets are *not* mapped. You -->
</web-app>
http://yourHost.com:8080/examples/test.php
.
Create a directory myApplication
, create the directories myApplication/WEB-INF/lib/
and myApplication/WEB-INF/cgi/
.
Download the J2EE binary and copy the JavaBridge.jar
and the php-servlet.jar
from the JavaBridge.war to the myApplication/WEB-INF/lib/
folder. Copy the contents of the cgi
folder to myApplication/WEB-INF/cgi/
. Create the file myApplication/WEB-INF/web.xml
with the following content:
<web-app>
<!-- PHP Servlet -->
<servlet>
<servlet-name>PhpJavaServlet</servlet-name>
<servlet-class>php.java.servlet.PhpJavaServlet</servlet-class>
</servlet>
<!-- PHP CGI processing servlet, used when Apache/IIS are not available -->
<servlet>
<servlet-name>PhpCGIServlet</servlet-name>
<servlet-class>php.java.servlet.PhpCGIServlet</servlet-class>
</servlet>
<!-- PHP Servlet Mapping -->
<servlet-mapping>
<servlet-name>PhpJavaServlet</servlet-name>
<url-pattern>*.phpjavabridge</url-pattern>
</servlet-mapping>
<!--PHP CGI Servlet Mapping -->
<servlet-mapping>
<servlet-name>PhpCGIServlet</servlet-name>
<url-pattern>*.php</url-pattern>
</servlet-mapping>
<!-- Welcome files -->
<welcome-file-list>
<welcome-file>index.php</welcome-file>
</welcome-file-list>
</web-app>
To call Java code from PHP, copy the java/Java.inc
to some directory and require it as usual, e.g.: require_once("java/Java.inc");
.
To call PHP code from Java, copy the java/JavaProxy.php
to some webdirectory and use the EngineFactory as usual, e.g.: EngineFactory.getInvocablePhpScriptEngine(this, application, request, response);
or, if PHP is running somewhere else: EngineFactory.getInvocablePhpScriptEngine(..., 80, "/phpApp/JavaProxy.php");
.
Copy the files sessionSharing.jsp
and sessionSharing.php
from the JavaBridge.war
to myApplication
and create myApplication.war
, for example with the commands: cd myApplication; jar cf ../myApplication.war *
.
The web archive can now be distributed, copy it to the tomcat webapps
directory and re-start tomcat. Visit http://localhost/myApplication/sessionSharing.php
and http://localhost/myApplication/sessionSharing.jsp
.
Install the PHP/Java Bridge for all web application as described here.
Set up Apache or IIS so that it forwards requests to the back end. Please see the description above for details.
No. The bridge back end is written in pure java, it doesn't use any native code. Native PHP runs within Apache, IIS, a FCGI server or via CGI. If the PHP instance crashes, an error page is returned to the client and the Apache, IIS, CGI container usually starts a new PHP instance for the next request.
If you see the message:
Warning: fsockopen() [function.fsockopen]: unable to connect to ssl://127.0.0.1:8443
(Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP?)
this means that PHP cannot connect back to the official SSL port.
Please check the
"Registered Stream Socket Transports" from the phpinfo()
(see the test.php
page), it should display: tcp, udp, ssl, sslv3, sslv2, tls
. If not, please recompile PHP with SSL enabled, use the flag --with-openssl
.
A workaround is to use the official non-SSL port or to open a dedicated local port for the PHP-Java communication. The following example is for Tomcat:
override_hosts
in the web application WEB-INF/web.xml
:
<context-param>
<param-name>override_hosts</param-name>
<param-value>Off</param-value>
</context-param>
Either fetch the Java.inc
directly from your back end (which also adjusts the JAVA_HOSTS
) or change the JAVA_HOSTS
option, for example:
define("JAVA_HOSTS", "127.0.0.1:9090");
Restart the application server or servlet engine. Check the settings by running phpinfo()
or by visiting the test.php
page.
It's a JBoss problem, although this problem may also appear in other application servers which do not strictly separate the application/bean domains. The JavaBridge.war already contains the documentClient.jar
as a library, so JBoss references the library classes instead of the bean classes. Just remove the documentClient.jar
from the JavaBridge.war
, re-deploy JavaBridge.war
and run the test again.
In JBoss' default setup the code:
// access the home interface
$DocumentHome = new JavaClass("DocumentHome");
$PortableRemoteObject = new JavaClass("javax.rmi.PortableRemoteObject");
$home=$PortableRemoteObject->narrow($objref, $DocumentHome);
refences the DocumentHome
from the library, which is assignment-incompatible to DocumentHome
from the enterprise bean (DocumentHome@WebAppClassLoader
!= DocumentHome@BeanClassLoader
), so you get a ClassCastException in narrow
.
In contrast the Sun J2EE server correctly separates the beans/applications; the $objref
is a unique proxy generated by a parent of the WebAppClassLoader
, so that narrow
can always cast the proxy to DocumentHome@WebAppClassLoader
, even if a class with the same name is already available from the WebAppClassLoader
.
By providing JSR 223 based PHP beans and a description how to manage them, as usual. The code
javax.script.ScriptEngine e =
php.java.script.EngineFactory.getInvocablePhpScriptEngine (this,
application,
request, response);
can be used to access the JSR 223 ScriptEngine from the framework, provided that a listener has been configured in the WEB-INF/web.xml:
<listener>
<listener-class>php.java.servlet.ContextLoaderListener</listener-class>
</listener>
With the java
function, for example: java("java.lang.System")
.
The function is defined in http://localhost:8080/JavaBridge/java/Java.inc
as:
function java($clazz) {
static $classMap = array();
if(array_key_exists($clazz, $classMap)) return $classMap[$clazz];
return classMap[$clazz]=new JavaClass($clazz);
}
PHP scripts must explicitly allocate a session with java_session()
. For example:
java_session();
// now the (Remote-)HttpServletRequest knows about the session:
echo java_context()->getHttpServletRequest()->getSession();
System.out
and
System.err
are redirected to the server log file(s). When
PHP scripts are invoked from a java framework (Java Server Faces for
example), even the PHP output is redirected. For the standalone back
end the output appears in the
/var/log/php-java-bridge.log
or in VMBridge.log, see
.ini option java.log_file
. For the j2ee back end the
location of the log file(s) depends on the j2ee server
configuration.
If you must code it yourself: with
e.g. java_session()->put("buf", $stringBuffer)
Request-handling threads are started
from a thread pool, which limits the number of user requests to 20
(default), see system property
php.java.bridge.threads
. All further requests have to
wait until one of the worker threads returns to the pool.
When running in a servlet engine, a ContextServer is started which handles the pipe or local socket communication channel.
When java invokes local scripts outside of a HTTP environment, the bridge starts a HttpServer, a ContextServer and a HttpProxy. The HttpProxy represents the PHP continuation and the HttpServer the request-handling java continuation associated with the JSR223 script.
classname$inner
syntax. For example
public interface php {
public class java {
public enum bridge {JavaBridge, JavaBridgeRunner};
}
}
<?php
java_require(getcwd()); // load php.class
$bridge = new java('php$java$bridge');
echo $bridge->JavaBridgeRunner;
?>
Primitive types are wrapped by associated java classes.
The following example uses reflect.Array
to create a new byte
array:
$Byte = new JavaClass("java.lang.Byte");
$byte = $Byte->TYPE;
$Array = new JavaClass("java.lang.reflect.Array");
$byteArray = $Array->newInstance($byte, 255);
$System = new JavaClass("java.lang.System");
$length = $System->in->read($byteArray);
$str = new Java("java.lang.String", $byteArray, 0, $length);
echo "You have typed: $str\n";
The following scripts were executed on one 1.688 GHZ x86 cpu running RedHat Fedora Core 4 Linux and Sun jdk1.6.0_02:
The PHP 5.2.2 code
<?php
$buf=new java("java.lang.StringBuffer");
$i=0;
while($i<400000) {
$i=$i+1;
$buf->append($i);
}
print $buf->length() . "\n";
?>
buf = new java.lang.StringBuffer();
for(i=0; i<400000; i++) buf.append(new String(i));
print (buf.toString().length());
Command | Script Engine | Communication Channel | Execution time (real, user, sys) |
---|---|---|---|
time jrunscript -l php t11.php | PHP5 + VM Bridge 4.3.3 | named pipes | 0m18.703s, 0m16.209s, 0m0.138s |
time jrunscript -l js t11.js | ECMA script | none (native code) | 0m15.338s, 0m14.996s, 0m0.116s |
OutOfMemoryErrors may happen because a cached object cannot be released, either because
When a java.lang.OutOfMemoryError
reaches the request-handling thread, the VM Bridge thread pool removes the thread from its pool and writes a message FATAL: OutOfMemoryError
to the VM Bridge log file. The session store is cleaned and all client connections are terminated without confirmation.
If the OutOfMemoryError persists, this means that a thread outside of the VM Bridge has caused this error condition.
OutOfMemory conditions can be debugged by running the back end with e.g.:
java -agentlib:hprof=heap=sites -jar JavaBridge.jar
By using java_closure()
and the visitor pattern for example. The tests.php5
folder contains a script_api.php
example which shows how to implement java.lang.Runnable
to run multiple PHP threads, concurrently accessing a shared resource.
With java_begin_document()/java_end_document()
. For example:
java_begin_document();
$s = new Java("java.lang.StringBuffer");
for($i=0; $i<10000; $i++) $s->append($i);
java_end_document();
The above code sends the PHP code as an XML image to the server and executes it there.
With java_values()
. For example:
$s = new Java("java.lang.String");
$c = $chr = $s->toCharArray();
print (java_values($s));
print_r(java_values($c));
With java_closure()
. For example:
class Foo {
function toString() {return "php::foo";}
}
$foo = new Foo();
$jObj = java_closure($foo);
$String = new Java("java.lang.String");
echo $String->valueOf($jObj);
Example:
require_once("http://localhost:8080/JavaBridge/java/Java.inc");
java_require("myLibs/baz-taglib.jar");
$tag = new Java("foo.bar.BazTag");
$session = java_session();
$ctx = java_context();
$servlet = $ctx->getAttribute("php.java.servlet.Servlet");
$response = $ctx->getAttribute("php.java.servlet.HttpServletResponse");
$request = $ctx->getAttribute("php.java.servlet.HttpServletRequest");
$factory = java("javax.servlet.jsp.JspFactory")->getDefaultFactory();
$pc = $factory->getPageContext($servlet, $request, $response, null, true, 8192, false);
$tag->setPageContext($pc);
$value = $tag->doStartTag();
if(($value != Java("javax.servlet.jsp.tagext.Tag")->SKIP_BODY) {
if($value != Java("javax.servlet.jsp.tagext.Tag")->EVAL_BODY_INCLUDE)) {
$tag->setBodyContent($pc->pushBody());
$tag->doInitBody();
}
do {
...
} while($tag->doAfterBody() == Java("javax.servlet.jsp.tagext.BodyTag")->EVAL_BODY_AGAIN)
}
if($value != Java("javax.servlet.jsp.tagext.Tag")->EVAL_BODY_INCLUDE) $pc->popBody();
$tag->doEndTag();
The generated content (if any) can be retrieved from the servlet output stream with:
java_values($response->getBufferContents();
Please see the php_java_lib/JspTag.php
and tests.php5/tag.php
for details.
You can ignore the parameter type.
Java doesn't support real generics on byte-code level. The generics in JDK 1.5 and above are implemented as "erasures"; they are syntactic sugar, useful only for the Java compiler. The generated byte-code is the same as in JDK 1.4.
Pass them as a PHP array. Example:
<?php require_once("http://localhost:8080/JavaBridge/java/Java.inc");
$here=getcwd(); java_require("$here/varargs.jar");
$t1 = new java('Varargs$Test', 1);
$t2 = new java('Varargs$Test', 2);
echo java("Varargs")->varargs(array($t1, $t2));
?>
public class Varargs {
public static class Test {
public int i;
public Test (int i) {
this.i = i;
}
public String toString() {
return String.valueOf(i);
}
}
public static String varargs(Test ...tests) {
StringBuffer buf = new StringBuffer();
for (Test test : tests) {
buf.append(test);
}
return buf.toString();
}
}
Use java_is_null($value)
or is_null (java_values ($value))
to test for a (Java-) NULL value.
Simply deploy the VM Bridge web archive into the servlet engine or application server listening on port 8080. Or use a different port.
The standalone option SERVLET_LOCAL emulates a servlet engine and starts a HTTP server which can select the fastest channel supported on this operating system. On Linux this is a named pipe created in /dev/shm or INET_LOCAL as a fall back.
INET_LOCAL always uses local TCP socket communication.
Download and install a servlet engine or J2EE server as a Windows or Unix service.
In order to communicate with Java, a PHP "Java" class definition is needed. Here's a simple PHP "Java" class definition which fits into one line:
<?php
// The following is the "Java" class definition, stripped down to fit into one line
// To use this sample start Java with: java -jar JavaBridge.jar INET:9267
// Or enable java.so or php_java.dll, which automatically start the above
// process Then type: php sample.php
//
class P {const Pc="<C v=\"%s\" p=\"I\">", PC="</C>"; const Pi="<I v=\"%d\" m=\"%s\" p=\"I\">", PI="</I>"; const Ps="<S v=\"%s\"/>", Pl="<L v=\"%d\" p=\"%s\"/>", Po="<O v=\"%d\"/>"; private $c; function str($s){fwrite($this->c, sprintf(self::Ps, $s));} function obj($s){fwrite($this->c, sprintf(self::Po, $s->java));} function __construct(){$this->c=fsockopen("127.0.0.1",9267);} function cBeg($s){fwrite($this->c, sprintf(self::Pc, $s));} function cEnd(){fwrite($this->c, self::PC);} function iBeg($o, $m){fwrite($this->c, sprintf(self::Pi, $o, $m));} function iEnd(){fwrite($this->c, self::PI);} function val($s){if(is_object($s))$this->obj($s);else $this->str((string)$s);} function res(){$r=sscanf(fread($this->c, 8192),"%s v=\"%[^\"]\"");return $r[1];}} function gP() {static $p; if(!$p) $p=new P(); return $p;} class Java {var $java, $p; function __construct() {if(!func_num_args()) return; $this->p=gP(); $ar=func_get_args(); $this->p->cBeg(array_shift($ar)); foreach($ar as $arg) $this->p->val($arg); $this->p->cEnd(); $ar = sscanf($this->p->res(), "%d"); $this->java=$ar[0];} function __call($meth, $args) {$this->p->iBeg($this->java, $meth); foreach($args as $arg) $this->p->val($arg); $this->p->iEnd(); $proxy = new Java(); $ar = sscanf($this->p->res(), "%d"); $proxy->java=$ar[0]; $proxy->p=$this->p; return $proxy;} function toString() {$this->p->iBeg("", "castToString"); $this->p->val($this); $this->p->iEnd(); return base64_decode($this->p->res());}}
// Test
$i1 = new Java("java.math.BigInteger", "1");
$i2 = new Java("java.math.BigInteger", "2");
$i3 = $i1->add($i2);
echo $i3->toString() . "\n";
?>
The above simple "Java" class assumes that some Java VM has been
started on host "127.0.0.1", port "9267". And it cannot handle values
larger than 8192 bytes. Therefore the VM Bridge
library Java.inc
should be used. Scripts should contain
the statement
require_once("...java/Java.inc");
at the beginning of each script. PHP compiles and caches PHP scripts, the Java.inc
library is loaded only once.