我正在尝试访问数组中的静态类成员变量。
我的代码(index.php):
<?php
class Foo
{
public static $staticVar = 'test';
}
class Bar
{
public $someArray = array(
Foo::$staticVar
);
}
$cls = new Bar();
var_dump($cls->someArray);
?>在PHP-7.0上,我得到了以下错误:
PHP致命错误:常量表达式包含行12中/var/www/html/index.php中的无效操作
在PHP-5.6中,我得到了以下错误:
Parse :语法错误,意外的'$staticVar‘(T_VARIABLE),期望第11行中/var/www/html/index.php中的标识符(T_STRING)或类(T_CLASS)
我只想让字符串"test“在我的数组中。
奇怪的是,当我“回音”出变量时,它的工作方式与预期的一样:
echo Foo::$staticVar // prints 'test'我是PHP新手,我不知道自己做错了什么。
发布于 2016-05-04 11:40:23
不幸的是,您不能在类属性的初始声明中引用另一个变量或类。这只是对现有语言的限制。一般的解决方法是初始化构造函数中的属性。
class Bar
{
public $someArray = array();
public function __construct()
{
$this->someArray = array(
Foo::$staticVar
);
}
}在一个模糊相关的说明中,PHP5.6至少在允许将常量定义为基本表达式方面取得了一些进展,请参阅https://3v4l.org/6TDZV
https://stackoverflow.com/questions/37026387
复制相似问题