爆炸时解析错误

时间:2016-03-09 22:41:44

标签: php parse-error

我收到了一个解析错误,并且不知道为什么

<?php
class api{
    //$api_Key;
    public function getURL($url){
        return file_get_contents($url);
    }
    public function postURL($url){
        $data = array();                                                                    
        $data_string = json_encode($data);   
        $ch = curl_init( $url );
        curl_setopt( $ch, CURLOPT_POST, 1);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        $response = curl_exec( $ch );
        print curl_error($ch);
        echo curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $response;
    }
} 
class geo extends api{
    public function getLocation(){
        return $this->getJSON($this->postURL("https://www.googleapis.com/geolocation/v1/geolocate?key="));
    }
}
class vote extends api {
    private $key = "";
    //private $cordinates = $_COOKIE["cord"];
    private $cookie = explode(',',$_COOKIE['cord']);
    function getElections(){
        return $this->getJSON($this->postURL("https://www.googleapis.com/civicinfo/v2/elections?fields=elections&key=$key"));
    }
    function getLocationInfo(){
        $lat = $cookie[0];
        $long = $cookie[1];
        return $this->getJSON($this->postURL("https://maps.googleapis.com/maps/api/geocode/json?latlng=".$lat",".$long."&key=$key"));
    }
    function getDivision(){

    }
}

?>

这是错误所在的行

private $cookie = explode(',',$_COOKIE['cord']);

这是错误

  

解析错误:第30行的G:\ wamp \ www \ voting \ php \ vote.php中的语法错误,意外'(',期待','或';'

我查看了文档并围绕此网站,语法看起来正确,但仍然无法通过此错误

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

1 个答案:

答案 0 :(得分:3)

在类中,您不能使用函数声明属性。

您可以使用__construct()

class vote extends api {
    private $key = "";
    //private $cordinates = $_COOKIE["cord"];
    private $cookie = array();

    function __construct(){
        $this->cookie = explode(',',$_COOKIE['cord']);
    }

    (...)

}

请注意:

我根据你自己的例子写了上面的例子,其中父类没有__construct()。如果真正的父类具有__construct()方法,则必须以这种方式修改代码:

function __construct( $arg1, $arg2, ... ){
    parent::__construct( $arg1, $arg2, ... );
    $this->cookie = explode(',',$_COOKIE['cord']);
}

$arg1等...是父类__construct()的参数: