简体   繁体   English

PHP(新)对象的数组

[英]PHP Array of (new) objects

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. 我正在开发一个基于Web的管理前端,用于我开发的应用程序,用PHP(在几次失败的尝试让Lua使用Apache和Nginx之后也有点奇怪)并且PHP的数组令我感到沮丧。

I'm trying to initialize an array of objects as I would in any other OOP-capable language: 我正在尝试初始化一个对象数组,就像在任何其他支持OOP的语言中一样:

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? 我是否必须通过使用临时变量和array_push来解决这个问题?

EDIT : I'm coming from OOP languages such as C#, Java and C++, as well as pure procedural languages such as Lua. 编辑:我来自OOP语言,如C#,Java和C ++,以及纯过程语言,如Lua。

Move the initialization part in the class' constructor __construct() . 在类的构造函数__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. 创建new对象是在代码执行期间发生的活动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM