【问题标题】:PHP Parse error using DIRECTORY_SEPARATOR in class variable在类变量中使用 DIRECTORY_SEPARATOR 解析 PHP 错误
【发布时间】:2014-07-10 08:00:47
【问题描述】:

为什么我可以分配

$tmpPath = DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;

在类方法中,但当我尝试将其分配给这样的受保护类变量时出现 PHP Parse 错误:

protected $_tmpPath = DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;

这是错误日志:

PHP Parse error: syntax error, unexpected '.', expecting ',' or ';' in ...

【问题讨论】:

    标签: php parse-error php-parse-error


    【解决方案1】:

    属性值必须是单个常量值,而不是表达式。

    除非您使用的是 PHP5.6,在这种情况下,您拥有的代码是完全允许的。

    但在您这样做之前,典型的解决方法是在类的构造函数中为其分配值。

    【讨论】:

    • 所以你所说的单一值是指任何不需要评估为值的东西?那么例如,字符串的连接是单个值还是表达式呢?找不到合适的定义。
    • 连接是一个表达式。
    • 文档说The simplest yet most accurate way to define an expression is "anything that has a value". php.net/manual/en/language.expressions.php 但是这与这个答案相冲突,因为'abcd' 肯定也是一个表达式并且允许用于属性值PHPpublic foo = DIRECTORY_SEPARATOR;) 也允许使用常量
    • 这就是文档中关于初始化属性的说法:php.net/manual/en/language.oop5.properties.phpThis 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. 所以 NietTheDarkAbsol 谈到“单值”与“表达式”时,他应该说“常量”
    • @nl-x 已编辑,这样更好吗?
    猜你喜欢
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多