【问题标题】:PHP: unexpected T_VARIABLE when initializing associative array [closed]PHP:初始化关联数组时出现意外的 T_VARIABLE [关闭]
【发布时间】:2013-06-02 16:53:51
【问题描述】:

我收到以下错误 Parse error: syntax error, unexpected T_VARIABLE in path/queries.php on line 92

因为数组$_queryArray

private $_queryA = "";
etc...
private $_queryV = "";


private $_queryArray = array(   'A' => $this->_queryA, //<= line 92 of my code
                                'B' => $this->_queryB,
                                'C' => $this->_queryC,
                                'D' => $this->_queryD,
                                'E' => $this->_queryE,
                                'F' => $this->_queryF,
                                'G' => $this->_queryG,
                                'H' => $this->_queryH,
                                'I' => $this->_queryI,
                                'J' => $this->_queryJ,
                                'K' => $this->_queryK,
                                'L' => $this->_queryL,
                                'M' => $this->_queryM,
                                'N' => $this->_queryN,
                                'O' => $this->_queryO,
                                'P' => $this->_queryP,
                                'Q' => $this->_queryQ,
                                'R' => $this->_queryR,
                                'S' => $this->_queryS,
                                'T' => $this->_queryT,
                                'U' => $this->_queryU,
                                'V' => $this->_queryV 
                            );

我填写$_queryArray ?的方式有问题吗

谢谢!

【问题讨论】:

    标签: php associative-array parse-error


    【解决方案1】:

    由于 $this 引用了一个实例,并且在定义类时不存在,因此您不能在属性定义中使用 $this

    引用docs

    这个声明可能包含一个初始化,但是这个初始化必须是一个常量值——也就是说,它必须能够在编译时被评估,并且不能依赖于运行时信息才能被评估。

    【讨论】:

    • 将其设为空数组,并在构建查询时将其填充到构造函数中
    • 更好的是,把它变成一个getter函数。
    【解决方案2】:

    我假设代码来自类声明。

    我的猜测是此时您无法访问 $this。 尝试在构造函数中设置数组。

    function __construct() {
        $this->_queryArray = array( ... );
    }
    

    【讨论】:

    • 很好看,不过还是太本地化了。
    • 我可以做到,但我在将查询放入数组之前以静态方式填充查询。如果构造函数有 200 行静态填充 no :s 会很丑陋?
    • 那些 $_query_A 类型的变量在我看来并不是特别静态
    • 而且你不需要200行数组填充,你使用一个循环
    猜你喜欢
    • 2012-08-25
    • 1970-01-01
    • 2012-02-26
    • 2013-12-25
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    • 2022-10-08
    • 1970-01-01
    相关资源
    最近更新 更多