在创建应用程序时,我遇到了一种情况,我有一个静态变量。
假设是:
public static name = "abdul ahad";
接下来,我在某个地方有另一个名为 user 的静态变量,它访问上面定义的静态变量名称。
public static user = self::$name;
Note: those properties are members of the same class.
这样做会出现以下错误。
解析错误:语法错误,意外的“$XXX”(T_VARIABLE),第 xx 行 C:\xxxx\xxx\xxx.php 中需要标识符 (T_STRING) 或类 (T_CLASS)
同样的概念也适用于Java,如下所示。
public static int i = 5;
public static int j = Main.i;
public static void main(String[] args) {
System.out.println(String.format("Static j was : %d", Main.j));
所以,我想知道在 PHP 中是否可能以及我在语法上做错了什么。如果不是,那么您愿意解释一下原因吗?
最佳答案
静态声明在编译时进行评估,因此您无法使用另一个变量初始化静态属性(无论它是否是静态的)。
来自documentation :
Like any other PHP static variable, static properties may only be initialized using a literal or constant before PHP 5.6; expressions are not allowed. In PHP 5.6 and later, the same rules apply as const expressions: some limited expressions are possible, provided they can be evaluated at compile time.
注意:您发布的错误消息很可能来自您未与我们共享的某些代码。另外,您的代码中还有另一个错误:
public static user = self::$name;
// ^
// the actual error
它应该产生以下错误消息:
PHP Parse error: syntax error, unexpected 'user' (T_STRING), expecting variable (T_VARIABLE) in ...
PHP 中的每个变量都必须有 $
(美元符号)前缀,因此正确的属性声明应如下所示:
public static $user = self::$name;
但是,正如我上面所写,您无法使用变量初始化静态属性,因此会产生以下错误:
PHP Fatal error: Constant expression contains invalid operations in ...
仅供比较,您帖子中的错误消息:
Parse error: syntax error, unexpected '$XXX' (T_VARIABLE), expecting identifier (T_STRING) or class (T_CLASS) in ...
关于java - 静态属性访问PHP中的静态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47142609/