[英]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
解析错误:语法错误,第12行的D:\\ web \\ www \\ poll \\ get_user_info \\ get_user_info.php中的意外T_VARIABLE
When I changed the 2 $_SERVER vars to simple strings the error disappeared. 当我将2 $ _SERVER变量更改为简单字符串时,错误消失了。
So what's the problem with $_SERVER in declaring class properties? 那么$ _SERVER在声明类属性时会出现什么问题?
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. 您可以创建__construct()方法,您可以以任何方式初始化属性。
So what's the problem with $_SERVER in declaring class properties?
那么$ _SERVER在声明类属性时会出现什么问题?
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? 以下是对原因的一些深入讨论: 为什么PHP属性不允许函数?
The bottom line however is, it's simply not possible. 然而,最重要的是,它根本不可能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.