Unable to call function in array

I am trying to call a function inside an array as follows:

protected $settings = array(
        'prefix' => $this->getPrefix(),
    );

expression not allowed as default field

getPrefix ()

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

I can not do it?

+4
source share
2 answers

Judging by your keyword protected, you are trying to set an object property. According to the PHP manual :

They are defined using one of the keywords public, protected or private, followed by the declaration of a normal variable. This declaration may include initialization, but this initialization must be a constant value, that is, it must be able to be evaluated at compile time and should not depend on runtime information for evaluation.

, :

class Settings
{
    protected $settings;

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

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

PHP. .

class MyClass
{
    protected $settings = array();

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

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

Source: https://habr.com/ru/post/1627310/


All Articles