Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Class $_SERVER Variable a Property

I'm developing a class and I have this structure:

class userInfo {
    public $interval        = 60;
    public $av_langs        = null;

    public $ui_ip           = $_SERVER['REMOTE_ADDR'];
    public $ui_user_agent   = $_SERVER['HTTP_USER_AGENT'];

    public $ui_lang         = null;
    public $ui_country      = null;

    // non-relevant code removed
}

But when executing the script I get this error:

Parse error: syntax error, unexpected T_VARIABLE in D:\web\www\poll\get_user_info\get_user_info.php on line 12

When I changed the 2 $_SERVER vars to simple strings the error disappeared.

So what's the problem with $_SERVER in declaring class properties?

Thanks

like image 460
medk Avatar asked Nov 30 '22 16:11

medk


2 Answers

Use this code as a guide:

public function __construct() {
    $this->ui_ip = $_SERVER['REMOTE_ADDR'];
    $this->ui_user_agent = $_SERVER['HTTP_USER_AGENT'];
}
like image 168
Chris Whittington Avatar answered Dec 10 '22 08:12

Chris Whittington


Property can be declared only with value, not expression.
You can create __construct() method, where you can initialize properties in any way.

like image 22
OZ_ Avatar answered Dec 10 '22 09:12

OZ_