aza*_*c2s 6 php static reference
要么我太笨了,要么这在php中是不可能的(这实际上是任何编程语言的基本功能......):所以这是我的问题的示例:
class Test {
private static $A = "test";
private static $B = "This is a " . Test::$A . " to see if it works";
}
Run Code Online (Sandbox Code Playgroud)
我的预期结果是变量$B的值 =This is a test to see if it works
但不知何故我收到了这个错误:
解析错误:语法错误,意外的“$A”(T_VARIABLE),第 4 行 /.../class.Test.php 中期望标识符(T_STRING)或类(T_CLASS)
这是php无法做到的事情还是只是一些愚蠢的拼写错误?我无法找到错误,因为大约一个小时了......
提前致谢
小智 0
如果您不想再有另一个班级,还有另一个解决方案
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';
}
}
Run Code Online (Sandbox Code Playgroud)
}
echo TestStatic::getB();
Run Code Online (Sandbox Code Playgroud)