简体   繁体   中英

How to inject java instances into PHP scripts programmatically executed using Quercus

I have some code similar to this:

QuercusEngine engine = new QuercusEngine();
Value value = engine.execute("<?php return $obj->getName(); ?>");
System.out.println(value);

(See http://wiki.caucho.com/Quercus:_Command_Line_Interface_(CLI) for more info)

I want to set $obj as a java instance. Something like this:

SomeObject someObject = new SomeObject();
engine.setParam("obj", someObject);

Obviously this is a simplistic example but the point is that I want to be able to use instances of java classes that have already been instantiated in the php script. How could I do this?

I don't think this is documented anywhere, but after looking through the source code, looking at what the QuercusEngine was doing, and a little trial and error this is what it takes:

Path path = new StringPath("<?php return $obj->getName(); ?>");
QuercusContext quercusContext = new QuercusContext();
ReadStream reader = path.openRead();
QuercusProgram program = QuercusParser.parse(quercusContext, null, reader);
WriteStream out = new WriteStream(StdoutStream.create());
QuercusPage page = new InterpretedPage(program);

Env env = new Env(quercusContext, page, out, null, null);

SomeObject someObj = new SomeObject();

JavaClassDef classDef = env.getJavaClassDefinition(someObject.getClass());
env.setGlobalValue("obj", new JavaValue(env, someObject, classDef));

Value value = NullValue.NULL;

try {
  value = program.execute(env);
}
catch (QuercusExitException e) {
}

out.flushBuffer();
out.free();

System.out.println(value);

Hope this helps someone. I tested this in Quercus 4.0.25.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM