【问题标题】:How to include variable inside class and use it? [duplicate]如何在类中包含变量并使用它? [复制]
【发布时间】:2016-01-14 18:18:39
【问题描述】:

我不明白为什么这个变量在这个类中不起作用,出现以下错误:

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


【解决方案1】:

PHP manual page on properties:

[属性]声明可以包含一个初始化,但是这个初始化必须是一个常量值——也就是说,它必须能够在编译时被评估,并且不能依赖运行时信息才能被评估.


要执行您正在尝试的操作,您可以改为在构造函数中对其进行初始化:

class socialCounter
{
    public $url;

    public function __construct()
    {
        $this->url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
    }

...

注意:您还缺少 getPlus(){...}$html = file_get_contents(... 行末尾的右括号。

【讨论】:

    【解决方案2】:

    你应该在这样的类中使用超全局变量

    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
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      你不能像这样分配$url 变量。如果你想这样做,我认为你应该想在构造函数上调用它。

      private $url;
      
      public function __construct()
      {        
          $this->url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
      }
      

      试试这个。

      【讨论】:

        猜你喜欢
        • 2015-08-17
        • 2023-03-04
        • 2014-02-07
        • 1970-01-01
        • 2020-02-19
        • 1970-01-01
        • 1970-01-01
        • 2013-04-10
        • 1970-01-01
        相关资源
        最近更新 更多