4

I'm trying to call a function inside array like this:

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

expression is not allowed as field of default value

getPrefix()

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

I can't do this?

2
  • 2
    No. Your object is not initiated while you define the object property, so the methods are not available. Simply do $this->settings['prefix'] = $this->getPrefix(); in the constructor of the object. Commented Feb 4, 2016 at 14:39
  • the warning is clear, expression is not allowed as field of default value, so you cannot use expression as a default value Commented Feb 4, 2016 at 14:42

2 Answers 2

4

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

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.

In order to set your value, put it into the constructor:

class Settings
{
    protected $settings;

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

    public function getPrefix() {
        return "Hello, World!";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Your object property must be defined when PHP compiles. However, you could simply initialize the value within your constructor.

class MyClass
{
    protected $settings = array();

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

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

1 Comment

I'd argue for a property, you should initialise them in the constructor

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.