有可能在php中的任何函数中添加回调吗?

Val*_*ran 0 php callback

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

on('json_encode',function(){
    echo "encoding something";
});
Run Code Online (Sandbox Code Playgroud)

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

mik*_*n32 6

不,你必须重写自己的包装函数.就像是:

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;
}
Run Code Online (Sandbox Code Playgroud)

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

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]";}
)
Run Code Online (Sandbox Code Playgroud)