Deprecated: Optional parameter $keys declared before required parameter $cms_id is implicitly treated as a required parameter in /home/www/dev/work/class/blog/CmsKey.php on line 75

Deprecated: Creation of dynamic property lvesu\lvesu\controller\blog\php::$title is deprecated in /home/www/dev/work/website/lvesu/class/controller/blog/php.php on line 28

Deprecated: Creation of dynamic property lvesu\lvesu\controller\blog\php::$outlink is deprecated in /home/www/dev/work/website/lvesu/template/blog/cms/php.manual.tpl on line 2

Deprecated: Creation of dynamic property lvesu\lvesu\controller\blog\php::$status is deprecated in /home/www/dev/work/website/lvesu/template/blog/index.head.php on line 2
PHP - Manual: PHP 回调 - 互联网笔记

略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: PHP 回调

2025-04-28

PHP 回调

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

示例 #1 将 PHP Closure 指派给 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!
虽然这样可以运行,但并非所有的 libffi 平台都支持这个功能,而且效率不高,并且在请求结束时会泄漏资源。
小技巧

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

添加备注

用户贡献的备注

此页面尚无用户贡献的备注。

官方地址:https://www.php.net/manual/en/ffi.examples-callback.php

冷却塔厂家 广告
中文GPT4.0无需注册 广告
北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3