【问题标题】:Cannot access static member variable from class in array无法从数组中的类访问静态成员变量
【发布时间】:2016-08-29 19:29:42
【问题描述】:

我正在尝试访问数组中的静态类成员变量。

我的代码(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 致命错误:常量表达式中包含无效操作 /var/www/html/index.php 第 12 行

在 PHP-5.6 上出现此错误:

PHP 解析错误:语法错误,意外的 '$staticVar' (T_VARIABLE), 期望标识符 (T_STRING) 或类 (T_CLASS) 在 /var/www/html/index.php 第 11 行

我只想在我的数组中包含字符串“test”。

奇怪的是,当我“回显”出变量时,它按预期工作:

echo Foo::$staticVar // prints 'test'

我是 PHP 新手,我不知道我做错了什么。

【问题讨论】:

    标签: php class oop static member


    【解决方案1】:

    不幸的是,您不能在类属性的初始声明中引用另一个变量或类。这只是语言本身的限制。一般的解决方法是在构造函数中初始化属性,例如

    class Bar
    {
        public $someArray = array();
    
        public function __construct()
        {
            $this->someArray = array(
                Foo::$staticVar
            );
        }
    }
    

    在一个模糊的相关说明中,PHP 5.6 至少在允许您将常量定义为基本表达式方面取得了一些模糊的进展,请参阅https://3v4l.org/6TDZV

    【讨论】:

    • 那么有什么解决方法可以将字符串放入数组中?我只是好奇如何摆脱该错误和/或使其更像“php方式”。
    • @hecaex 在答案中添加了一个示例
    猜你喜欢
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 2020-01-27
    • 2019-08-02
    • 2023-03-06
    相关资源
    最近更新 更多