【问题标题】:php constant in data member of a class [closed]类的数据成员中的php常量[关闭]
【发布时间】:2013-12-26 10:42:23
【问题描述】:

下面提到的代码有什么问题? 它抛出解析错误 PHP 解析错误:语法错误,意外的 '.',期待 ',' 或 ';'在第 9 行的 /home/gaurav/c.php 中

<?php

class b {
    const ABC = 'abc';
}

class c extends b {

    private $r = self::ABC ." d";
    function getABC()
    {
            echo $this->r;
    }
}

$c = new c();
$c->getABC();

【问题讨论】:

  • 你想要的已经回答了here

标签: php constants


【解决方案1】:

这个错误的原因是 PHP 不允许在类成员声明中使用表达式,即使只使用了常量元素。

所以private $r = self::ABC ." d"; 是不允许的,而private $r = self::ABC; 可以,正如 Gautam3164 回答的那样。

更多细节,例如这个答案: Initializing PHP class property declarations with simple expressions yields syntax error

【讨论】:

    【解决方案2】:

    http://www.php.net/manual/en/language.oop5.properties.php得到答案

    This declaration may include an initialization, but this initialization must be a constant   value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
    

    所以,在我的代码中 self::ABC ." d" 不是常数。

    【讨论】:

      【解决方案3】:

      你可以试试:

      private $r = self::ABC;
      $r = $r . "d";    
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-09-26
        • 2015-05-08
        • 1970-01-01
        • 1970-01-01
        • 2012-11-13
        • 2021-09-19
        • 1970-01-01
        相关资源
        最近更新 更多