1

I'm currently developing a web-based administration frontend, for an application I developed, in PHP (after several failed attempts to get Lua working with Apache and Nginx being a little weird, too) and PHP's arrays are frustrating me.

I'm trying to initialize an array of objects as I would in any other OOP-capable language:

private $leftNavItems = array(
        new LeftNavItem("./img/icon/status.png", "status", "App Status", "./articles/app_status.phtml", "app_status")
    );

however, I'm getting an error stating "expression not allowed as field default value".

Why can I not initialize an array with new objects? Would I have to work around this by using temporary variables and array_push?

EDIT : I'm coming from OOP languages such as C#, Java and C++, as well as pure procedural languages such as Lua.

11
  • what's your LeftNavItem? Commented May 26, 2017 at 13:33
  • It's a class with a couple variables, a constructor, and a couple getters. Commented May 26, 2017 at 13:33
  • 1
    Possible duplicate of Expression is not allowed as field default value Commented May 26, 2017 at 13:33
  • 2
    Move the initialization part in the class' constructor __construct(). Object properties can be initialized on their definition only with values that can be evaluated during compilation. Commented May 26, 2017 at 13:35
  • 1
    @Schleis I disagree, I'm asking not just for a way to work around, but also why this is a constraint. Also, I'm attempting to create an array of new objects, not initialize a value in a class. Commented May 26, 2017 at 13:35

1 Answer 1

3

Move the initialization part in the class' constructor __construct(). Object properties can be initialized on their definition only with values that can be evaluated during compilation.

class X {
    private $leftNavItems = array();

    public function __construct()
    {
        $this->leftNavItems = array(
            new LeftNavItem("./img/icon/status.png", "status", "App Status", "./articles/app_status.phtml", "app_status")
        );
    }
}

The initializers of the properties are evaluated during the compilation; they are not pieces of code to be executed when the class is initialized.

Your code attempts to initialize the variable by creating a object. Creating new objects is an activity that happens during the code execution.

Sign up to request clarification or add additional context in comments.

Comments

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.