我不明白为什么这个变量在这个类中不工作,出现以下错误:
Parse error: syntax error, unexpected '$_SERVER' (T_VARIABLE)
我读到它应该以以下方式使用:$this->url()
,但它似乎不像PHP允许变量也不是类中的超全局变量,有没有办法?
class socialCounter
{
public $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
public function getPlus()
{
$html = file_get_contents( "https://plusone.google.com/_/+1/fastbutton?url=".urlencode($this->url());
libxml_use_internal_errors(true);
$doc = new DOMDocument(); $doc->loadHTML($html);
$counter=$doc->getElementById('aggregateCount');
return $counter->nodeValue;
}
public function getTweets(){
$json = file_get_contents( "http://urls.api.twitter.com/1/urls/count.json?url=".$this->url() );
$ajsn = json_decode($json, true);
$cont = $ajsn['count'];
return $cont;
}
}
PHP属性手册页:
[属性]声明可以包含一个初始化,但是这个初始化必须是一个常数值——也就是说,它必须能够在编译时求值,并且不能依赖于运行时信息来求值。
你可以在构造函数中初始化它:
class socialCounter
{
public $url;
public function __construct()
{
$this->url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
}
...
注意:您还在$html = file_get_contents(...
行末尾的getPlus(){...}
中缺少右括号。
你应该在这样的类中使用超全局变量
class socialCounter
{
private $_httphost;
private $_phpself;
public function __construct()
{
$this->_httphost = $_SERVER['HTTP_HOST'];
$this->_phpself = $_SERVER['PHP_SELF'];
//use these variables inside your class functions
}
}
不能这样分配$url
变量。如果你想这样做,我认为你应该在构造函数中调用它。
private $url;
public function __construct()
{
$this->url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
}
试试这个。