简体   繁体   English

PHP:静态属性中的类实例引发异常

[英]PHP: Class instantiation in static property throws exception

I'd like to create a class (eg Bar ) which has a private static property. 我想创建一个具有私有静态属性的类(例如Bar )。 This property should be an array of objects of Foo . 此属性应该是Foo的对象数组。

<?php

class Foo {

}

class Bar {
    private static $classes = array(new Foo(), new Foo());

    public static function testClasses() {
        var_dump(self:$classes);
    }
}

Bar::testClasses();

However this code throws an exception: 但是,此代码引发异常:

PHP Parse error: syntax error, unexpected 'new' (T_NEW), expecting ')' in [...]/test.php on line 8

Can somebody explain me why this is not possible? 有人可以解释一下为什么这不可能吗?

From the docs : 文档

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. 该声明可以包括一个初始化,但是此初始化必须是一个常量值-也就是说,它必须能够在编译时进行评估,并且必须不依赖于运行时信息才能进行评估。

Your use of new to instantiate the classes in the property definition Is dependent on run-time information 您使用new实例化属性定义中的类取决于运行时信息

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

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