0

I can't understand as to why this variable isn't working inside this class, the following error shows up:

Parse error: syntax error, unexpected '$_SERVER' (T_VARIABLE)

I read that it should be used the following way: $this->url() but it doesn't seem like PHP allows variables nor superglobals inside classes, is there a way around this?

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;
    }
}
iBrazilian2
  • 2,204
  • 6
  • 23
  • 45

3 Answers3

4

PHP manual page on properties:

[The property] declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.


To do what you're attempting, you can instead initialize it in the constructor:

class socialCounter
{
    public $url;

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

...

Note: you're also missing a closing parenthesis in getPlus(){...} at the end of your $html = file_get_contents(... line.

user3942918
  • 25,539
  • 11
  • 55
  • 67
2

you should use superglobals inside a class like this

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
    }

}
Sumit Pandey
  • 448
  • 2
  • 9
1

You can not assign $url variable like this.If you want to do that I think You should want to called it on constructor.

private $url;

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

Try this.

UWU_SANDUN
  • 1,123
  • 13
  • 19