codecamp

PHP8 回调

可以将 PHP 闭包分配给函数指针类型的原生变量,或将其作为函数参数传递。

<?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!

虽然这样可以运行,但并非所有的 libffi 平台都支持这个功能,而且效率不高,并且在请求结束时会泄漏资源。

小技巧

因此,建议尽量减少使用 PHP 回调函数。


PHP8 基础 FFI 用法
PHP8 完整 PHP/FFI/preloading 示例
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定