v8js 是 php 中的一个扩展,使用 pecl install v8js 完成安装,这里不作介绍。
看官方的几个示例
<?php
class Foo {
var $bar = null;
}
$v8 = new V8Js();
$v8->foo = new Foo;
// This prints "no"
$v8->executeString('print( "bar" in PHP.foo ? "yes" : "no" );');
?>
<?php
class Foo {
var $bar = "bar";
function bar($what) { echo "I'm a ", $what, "!\n"; }
}
$foo = new Foo;
// This prints 'bar'
echo $foo->bar, "\n";
// This prints "I'm a function!"
$foo->bar("function");
$v8 = new V8Js();
$v8->foo = new Foo;
// This prints 'bar'
$v8->executeString('print(PHP.foo.$bar, "\n");');
// This prints "I'm a function!"
$v8->executeString('PHP.foo.__call("bar", ["function"]);');
?>
实践
js 获取 php 中的变量
<?php
$v8 = new V8Js();
$v8->bar = 'bar';
$v8->executeString('print(PHP.bar);');
获取 js 返回结果
<?php
$v8 = new V8Js();
$v8->bar = 6;
$result_var = $v8->executeString('var a=1;b=2;var c=a+b+PHP.bar;c;');
$result_function = $v8->executeString('function func(a){return a;}func(PHP.bar)');
配合 php 类使用
<?php
class Foo {
var $bar = null;
function func($what) {
$this->bar = $what;
echo $what;
}
}
$foo = new Foo;
echo $foo->bar;
$foo->func('function');
$v8->foo = new Foo;
// 访问类变量
$v8->executeString('print(PHP.foo.$bar)');
// 访问类方法
$v8->executeString('PHP.foo.__call("func", ["function"]);');