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
Use this code as a guide:
public function __construct() {
$this->ui_ip = $_SERVER['REMOTE_ADDR'];
$this->ui_user_agent = $_SERVER['HTTP_USER_AGENT'];
}
Property can be declared only with value, not expression.
You can create __construct() method, where you can initialize properties in any way.
So what's the problem with $_SERVER in declaring class properties?
You can't preset class properties with variables nor with function calls.
Here is some in-depth discussion on why: Why don't PHP attributes allow functions?
The bottom line however is, it's simply not possible.
精彩评论