From: <php...@li...> - 2006-11-17 18:40:34
|
Hi Verena, > PhpScriptEngine engine = new PhpScriptEngine(); > String s = "<?php \n"; > s += "java_context()->setAttribute( 'obj', new > MyClass(), 100 ); \n"; > s += "java_context()->call(java_closure()); \n"; > s += "?>"; > engine.eval( new StringReader(s) ); the above code should work, it evaluates the php script stored in the Java string s. However, you'll get a warning that the instance of MyClass is not a Java object. Use java_closure(new MyClass()) instead. > Invocable inv = (Invocable) engine; > inv.invokeMethod( engine.get("obj"), "saySomething", > new Object() ); You will get a null pointer exception because obj is bound to null, see the warning above. Furthermore you have captured the top-level environment, but you probably want to invoke methods from MyClass(). Frameworks such as Java Server Faces allow you to define PHP beans and to inject these beans into the framework: http://php-java-bridge.cvs.sourceforge.net/php-java-bridge/php-java-bridge/examples/java-server-faces/helloWorld.php?revision=1.6&view=markup java_context()->call(java_closure(new helloWorld())) ||include("index.php"); The above code creates an instance of the PHP helloWorld() class, creates a Java proxy for it and then calls the framework (the java_context()->call magic does this). When the call() failed (which means that the first request came in from the web server, and not from the framework), we redirect to index.php, which forwards the browser to the framework, which in turn evaluates the PHP script. The script creates the PHP bean and injects it into the framework. After that the framework holds a reference to the PHP bean and can call its methods: http://php-java-bridge.cvs.sourceforge.net/php-java-bridge/php-java-bridge/server/php/java/faces/Script.java?revision=1.6&view=markup return ((Invocable)((PhpFacesContext)FacesContext.getCurrentInstance()).getScriptEngine(this, new URL(script))).invoke(name, args); I think this is exactly what you want. The only difference is that the above method calls out to a URL instead of a local script file. > String script = "var obj = new Object(); > obj.hello = function(name) > { print('Hello, ' + name); }"; > Any chance todo something similar with PHP? It is certainly possible to automatically call java_closure(), when a php object is passed to a Java procedure. But for several reasons we've decided to require java_closure(php_object). Furthermore, if I understand the above code correctly, the "new Object()" above instanciates a Java object, not an object from the js script interpreter. Regards, Jost Boekemeier ___________________________________________________________ Telefonate ohne weitere Kosten vom PC zum PC: http://messenger.yahoo.de |