在PHP中声明默认类属性时,无法使用连接? [英] Cannot use concatenation when declaring default class properties in PHP?

查看:174
本文介绍了在PHP中声明默认类属性时,无法使用连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在PHP类中声明属性的默认值时,它似乎不能使用连接。是否有原因?

When declaring default values for properties in a PHP class, it appears you can not use concatenation. Is there a reason for this?

class Foo
{
    public $property = __DIR__ . '/';
}


推荐答案

/ h2>

请参阅 http: //www.php.net/manual/en/language.oop5.properties.php


它们是通过使用一个关键字public,protected或private,后跟一个正常的变量声明。这个声明可以包括一个初始化,但是这个初始化必须是一个常量值 - 也就是说,它必须能够在编译时被评估,并且不能依赖运行时信息来进行评估。

They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. 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.

对于更复杂的初始化,使用构造函数

For more complex initialisation, use the constructor

public function __construct()
{
    $this->settings = __DIR__ . '/';
}



PHP 5.6及以上



从PHP 5.6版开始,您可以在PHP中声明默认类属性时使用连接。请参见 https://wiki.php.net/rfc/const_scalar_exprs


这允许只有静态值(const声明,属性声明,函数参数等)的地方也能够获取静态表达式。

This allows places that only take static values (const declarations, property declarations, function arguments, etc) to also be able to take static expressions.

这篇关于在PHP中声明默认类属性时,无法使用连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆