可以将 PHP 闭包分配给本机函数指针类型的变量,或者将其作为函数参数传递。
示例 #1 将 PHP 闭包 分配给 C 函数指针
<?php
$zend = FFI::cdef("
typedef int (*zend_write_func_t)(const char *str, size_t str_length);
extern zend_write_func_t zend_write;
");
echo "Hello World 1!\n";
$orig_zend_write = clone $zend->zend_write;
$zend->zend_write = function($str, $len) {
global $orig_zend_write;
$orig_zend_write("{\n\t", 3);
$ret = $orig_zend_write($str, $len);
$orig_zend_write("}\n", 2);
return $ret;
};
echo "Hello World 2!\n";
$zend->zend_write = $orig_zend_write;
echo "Hello World 3!\n";
?>
上面的示例将输出
Hello World 1! { Hello World 2! } Hello World 3!
因此建议尽量减少 PHP 回调的使用。