可以在 php 中添加对任何函数的回调


Is possible to add a callback to any function in php?

我可以向 php 本机函数添加回调吗?

on('json_encode',function(){
    echo "encoding something";
});

如果是,是否可以添加帖子和预回调?谢谢。

不,您必须重写自己的包装器函数。像这样:

function my_json_encode($data) {
    if (function_exists("json_encode_pre_callback")) {
        json_encode_pre_callback();
    }
    $return = json_encode($data);
    if (function_exists("json_encode_post_callback")) {
        json_encode_post_callback($return);
    }
    return $return;
}

或者,使用回调作为参数:

function my_json_encode($data, $pre = null, $post = null) {
    if (is_callable($pre)) {
        $pre();
    }
    $return = json_encode($data);
    if (is_callable($post)) {
        $post($return);
    }
    return $return;
}
my_json_encode(
    $data,
    function(){echo "doing encode";},
    function($d){echo "done encode, value 1 is $d[1]";}
)

不,最好的方法是调用 PHP 本机函数的用户定义函数。

虽然,您可以使用override_function(请参阅此处的文档)重新定义PHP本机函数,但请注意,不再维护apd扩展。