我对这个问题感到困惑,存在未定义的变量


I am puzzled with this issue undefined variable exists

我正在尝试使用卷曲包装器进行 api 调用。我创建了一个新的 curl 对象,然后尝试引用它,它说我是未定义的。这是下面的错误,它指的是这一行。

$curl->get("https://maps.googleapis.com/maps/api/geocode/json",

注意:未定义的变量:curl 在第 18 行的 G:''wamp''www''voteting''php''vote.php

<?php
    require ('/vendor/autoload.php');
    use 'Curl'Curl;
    $key = "";
    $curl = new Curl();
    function getLat(){
        return explode(',',$_COOKIE['cord'])[0];
    }
    function getLong(){
        return explode(',',$_COOKIE['cord'])[1];
    }
    function getLocationInfo(){
        $lat = getLat();
        $long = getLong();
        $curl->get("https://maps.googleapis.com/maps/api/geocode/json",
            array(
                'latlng' => getLat().','.getlong(),
                'key' => $key,
            ));
        echo $curl->response->status;
    }
    function getDivision(){
    }

    ?>
<?php
    include("./php/vote.php");
    echo getLocationInfo();
    //echo $_COOKIE["cord"];
    ?>

显然:

function getLocationInfo(){
    $lat = getLat();
    $long = getLong();
    $curl->get("https://maps.googleapis.com/maps/api/geocode/json",
      ^---where does this get defined inside the function?

你还没有将$curl传递到你的函数中,所以它是未定义的。请阅读方法中的范围!

这应该可以解决它:

function getLocationInfo($curl){
        $lat = getLat();
        $long = getLong();
        $curl->get("https://maps.googleapis.com/maps/api/geocode/json",
            array(
                'latlng' => getLat().','.getlong(),
                'key' => $key,
            ));
        echo $curl->response->status;
    }

然后在调用函数时,添加参数 - $curl 。即:getLocationInfo($curl);

该问题是由变量作用域引起的。您已经定义了一个名为 $curl 的变量,该变量位于您尝试使用的函数范围的一侧。

你可以这样修复它:

function getLocationInfo(){
    global $curl;
    $lat = getLat();
    $long = getLong();
    $curl->get("https://maps.googleapis.com/maps/api/geocode/json",
        array(
            'latlng' => getLat().','.getlong(),
            'key' => $key,
        ));
    echo $curl->response->status;
}

另一种选择是将 curl 对象作为参数传递给函数,如下所示:

function getLocationInfo($curl){
    $lat = getLat();
    $long = getLong();
    $curl->get("https://maps.googleapis.com/maps/api/geocode/json",
        array(
            'latlng' => getLat().','.getlong(),
            'key' => $key,
        ));
    echo $curl->response->status;
}

您应该阅读 http://php.net/manual/en/language.variables.scope.php