php常量在类的数据成员中

时间:2013-12-09 10:48:16

标签: php const

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

<?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();

3 个答案:

答案 0 :(得分:0)

您可以尝试:

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

答案 1 :(得分:0)

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

所以private $r = self::ABC ." d";是不允许的,而private $r = self::ABC;是可以的,因为Gautam3164已经回答了。

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

答案 2 :(得分:0)

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”不是常数。