要么我太笨,要么这在 php 中是不可能的(这实际上是任何编程语言中的基本功能......):
所以这是我的问题的例子:
class Test {
private static $A = "test";
private static $B = "This is a " . Test::$A . " to see if it works";
}
我的预期结果是变量
$B
具有值 = This is a test to see if it works
但不知何故我收到了这个错误:
Parse error: syntax error, unexpected '$A' (T_VARIABLE), expecting identifier (T_STRING) or class (T_CLASS) in /.../class.Test.php on line 4
这是什么东西php是无法做到还是只是一些愚蠢的错字?大约一个小时后,我无法找到错误...
提前致谢
最佳答案
如果你不想有另一个类(class),另一种解决方案
class TestStatic
{
private static $A = 'test';
private static $B;
//if you want to instantiate the object
public function __construct() {
self::setB();
}
//if you don't want to instantiate the class
public static function getB() {
self::setB();
return self::$B;
}
private static function setB() {
if (!isset(self::$B)) {
self::$B = 'This is a '.self::$A.' to see if it works';
}
}
}
echo TestStatic::getB();
关于PHP:在静态变量中引用另一个静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39770649/