执行php文件
func Test_exec(t *testing.T) { engine.Initialize() ctx := &engine.Context{ Output: os.Stdout, } err := engine.RequestStartup(ctx) if err != nil { fmt.Println(err) } defer engine.RequestShutdown(ctx) err = ctx.Exec("/tmp/index.php") if err != nil { fmt.Println(err) }}
其中 /tmp/index.php 的内容为
<?phpecho("hello/n");
Eval,返回值
func Test_eval(t *testing.T) { engine.Initialize() ctx := &engine.Context{} err := engine.RequestStartup(ctx) if err != nil { fmt.Println(err) } defer engine.RequestShutdown(ctx) val, err := ctx.Eval("return 'hello';") if err != nil { fmt.Println(err) } defer engine.DestroyValue(val) if engine.ToString(val) != "hello" { t.FailNow() }}
返回的value的生命周期所有权是golang程序,所以我们要负责DestroyValue
设置全局变量来传参
func Test_argument(t *testing.T) { engine.Initialize() ctx := &engine.Context{} err := engine.RequestStartup(ctx) if err != nil { fmt.Println(err) } defer engine.RequestShutdown(ctx) err = ctx.Bind("greeting", "hello") if err != nil { fmt.Println(err) } val, err := ctx.Eval("return $greeting;") if err != nil { fmt.Println(err) } defer engine.DestroyValue(val) if engine.ToString(val) != "hello" { t.FailNow() }}
传递进去的参数的生命周期是php控制的,在request shutdown的时候内存会被释放。
PHP 回调 Golang
type greetingProvider struct { greeting string}func (provider *greetingProvider) GetGreeting() string { return provider.greeting}func newGreetingProvider(args []interface{}) interface{} { return &greetingProvider{ greeting: args[0].(string), }}func Test_callback(t *testing.T) { engine.Initialize() ctx := &engine.Context{} err := engine.RequestStartup(ctx) if err != nil { fmt.Println(err) } defer engine.RequestShutdown(ctx) err = engine.Define("GreetingProvider", newGreetingProvider) if err != nil { fmt.Println(err) } val, err := ctx.Eval(` $greetingProvider = new GreetingProvider('hello'); return $greetingProvider->GetGreeting();`) if err != nil { fmt.Println(err) } defer engine.DestroyValue(val) if engine.ToString(val) != "hello" { t.FailNow() }}
PHP 错误日志
func Test_log(t *testing.T) { engine.PHP_INI_PATH_OVERRIDE = "/tmp/php.ini" engine.Initialize() ctx := &engine.Context{ Log: os.Stderr, } err := engine.RequestStartup(ctx) if err != nil { fmt.Println(err) } defer engine.RequestShutdown(ctx) _, err = ctx.Eval("error_log('hello', 4); trigger_error('sent from golang', E_USER_ERROR);") if err != nil { fmt.Println(err) }}
其中 /tmp/php.ini 的内容为
error_reporting = E_ALLerror_log = "/tmp/php-error.log"
新闻热点
疑难解答