我很困惑这个问题存在未定义的变量

时间:2016-03-10 16:30:25

标签: php curl

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

  

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

     

注意:未定义的变量:第18行的G:\ wamp \ www \ voting \ 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"];
    ?>

3 个答案:

答案 0 :(得分:0)

显然:

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

答案 1 :(得分:0)

您尚未将$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);

答案 2 :(得分:0)

问题是由可变范围引起的。您已经定义了一个名为$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

相关问题