phpv8 / v8js

V8 Javascript Engine for PHP — This PHP extension embeds the Google V8 Javascript Engine
http://pecl.php.net/package/v8js
MIT License
1.83k stars 200 forks source link

Calling JS function from PHP? #33

Closed cscott closed 10 years ago

cscott commented 10 years ago

I'm using v8->executeString to evaluate some code like:

(function(exports) {
   // begin module code
   exports.hello = function() { return 'hello' };
   // end module code
   return exports;
})({})

That's a pretty standard wrapper for a CommonJS-style module definition. I get the exports object back in PHP land. I'd like to then call various (JavaScript) methods from it. But $exports->hello() gives me a V8 exception ("v8::HandleScope::CreateHandle() Cannot create a handle without a HandleScope"), and the other various ways I've tried to do this, like:

$v8->func = get_object_vars( $exports )['hello'];
$result = $v8->executeString("PHP.func()");

gives me complaints in JS land that func is "not a function" (it's a [object V8Function] apparently). What am I doing wrong?

stesie commented 10 years ago

hey, V8Js currently focuses on providing an API from PHP to JavaScript and initiate calls from JavaScript to PHP (and not the other way round). But still I agree that it would be cool if that would work as well. I'll maybe have a look soon :)

What indeed works is giving control from PHP to JavaScript (via executeString), then call from JavaScript back to PHP (which provides a HandleScope to V8Js/PHP) and then from PHP back to JavaScript (for some event callback or the like)

cheers stesie

cscott commented 10 years ago

I think the first part of this is still open? (Calling a returned JS function directly from PHP.)

cscott commented 10 years ago

Never mind, I see that was fixed by #39.