Php Can';数组中的t调用函数

Php Can';数组中的t调用函数,php,Php,我尝试调用数组中的函数,如下所示: protected $settings = array( 'prefix' => $this->getPrefix(), ); 表达式不允许作为默认值的字段 getPrefix() 我不能这样做?在PHP编译时必须定义对象属性。但是,您可以简单地在构造函数中初始化该值 class MyClass { protected $settings = array(); public function __cons

我尝试调用数组中的函数,如下所示:

protected $settings = array(
        'prefix' => $this->getPrefix(),
    );
表达式不允许作为默认值的字段

getPrefix()


我不能这样做?

在PHP编译时必须定义对象属性。但是,您可以简单地在构造函数中初始化该值

class MyClass
{
    protected $settings = array();

    public function __construct()
    {
        $this->settings['prefix'] => $this->getPrefix()
    }

    public function getPrefix()
    {
        return "hello world";
    }
}

根据
protected
关键字判断,您正在尝试设置对象属性。根据PHP的说法:

它们是通过使用关键字public、protected或private中的一个来定义的,后跟一个普通变量声明。该声明可能包含一个初始化,但该初始化必须是一个常量值——也就是说,它必须能够在编译时进行计算,并且必须不依赖于运行时信息才能进行计算

要设置值,请将其放入构造函数:

class Settings
{
    protected $settings;

    public function __constructor() {
        $this->settings = array(
            'prefix' => $this->getPrefix(),
        );
    }

    public function getPrefix() {
        return "Hello, World!";
    }
}

否。在定义对象属性时,对象未启动,因此方法不可用。只需执行
$this->settings['prefix']=$this->getPrefix()在对象的构造函数中。警告很清楚,
表达式不允许作为默认值的字段
,因此您不能将表达式用作默认值。我认为应该在构造函数中初始化它们
class Settings
{
    protected $settings;

    public function __constructor() {
        $this->settings = array(
            'prefix' => $this->getPrefix(),
        );
    }

    public function getPrefix() {
        return "Hello, World!";
    }
}