【问题标题】:What is the scope of CURLOPT_HEADERFUNCTION?CURLOPT_HEADERFUNCTION 的范围是什么?
【发布时间】:2017-04-19 00:16:03
【问题描述】:

TIA 为您提供帮助。

我正在使用 cURL 调用外部 REST API。通话效果很好。
作为 cURL 选项的一部分,我使用 CURLOPT_HEADERFUNCTION 来解析响应标头,如下所示:

curl_setopt($ch, CURLOPT_HEADERFUNCTION, "parseResponseHeaders");  

函数看起来像这样:

function parseResponseHeaders($ch, $header_line ) {
    if(preg_match("/Location/i", $header_line)){
        $break_header = explode(": ", $header_line);
        $build_new_string = $break_header[1].$string_from_outside_this_function;
    }
    return strlen($header_line);
}  

我遇到的问题是“$string_from_outside_this_function”变量返回未定义。

我了解“parseResponseHeaders”回调接受 2 个参数。所以我不能传递外部变量。
我假设外部变量不在范围内。但是,上面的代码包含在父函数(方法)中。 并且外部变量在父函数内的任何其他地方都可用。

不知道我做错了什么。

谢谢。

【问题讨论】:

    标签: php rest curl


    【解决方案1】:

    如果您的函数是匿名函数,您可以使用use 关键字将变量注入到与函数体中定义函数相同的范围内。

    看起来像这样:

    $string_from_outside_this_function = 'Testing';
    
    $parseResponseHeaders = function ($ch, $header_line) use ($string_from_outside_this_function) {
        //Thanks to the "use" keyword, "Testing" has been injected as the value of
        //$string_outside_this_function variable
        if (preg_match("/Location/i", $header_line)) {
            $break_header = explode(": ", $header_line);
            $build_new_string = $break_header[1].$string_from_outside_this_function;
        }
    
        return strlen($header_line);
    }
    

    现在您的匿名函数已定义,您可以像这样在 curl_setopt 调用中传递它:

    curl_setopt($ch, CURLOPT_HEADERFUNCTION, $parseResponseHeaders);
    

    这假定您的curl_setopt 调用发生的位置具有范围内的匿名函数变量。换句话说,您不能在一个范围内创建匿名函数,并在另一个范围内调用curl_setopt,并期望定义$parseResponseHeaders。这实际上会让您回到另一个地方的原始范围界定问题。

    这里是关于匿名函数的 PHP 文档,其中包括 use 关键字:http://php.net/manual/en/functions.anonymous.php

    请务必注意,命名函数不能使用use 关键字,只能使用匿名函数。这里回答了,供参考:Can non-anonymous functions in PHP using 'use' keyword?

    【讨论】:

    • 非常感谢@stratedge。你的解决方案对我有用。
    • 没问题@jnkrois,乐于助人!
    猜你喜欢
    • 2011-11-11
    • 2020-10-18
    • 2017-04-22
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多