Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP-定义对象的静态数组_Php_Arrays_Object - Fatal编程技术网

PHP-定义对象的静态数组

PHP-定义对象的静态数组,php,arrays,object,Php,Arrays,Object,您可以在PHP中初始化类中的静态对象数组吗?就像你能做的一样 class myclass { public static $blah = array("test1", "test2", "test3"); } 但当我这么做的时候 class myclass { public static $blah2 = array( &new myotherclass(), &new myotherclass(), &n

您可以在PHP中初始化类中的静态对象数组吗?就像你能做的一样

class myclass {
    public static $blah = array("test1", "test2", "test3");
}
但当我这么做的时候

class myclass {
    public static $blah2 = array(
        &new myotherclass(),
        &new myotherclass(),
        &new myotherclass()
    );
}
其中MyTherClass定义在myclass的正上方。 然而,这是一个错误;有没有办法做到这一点?

没有。发件人:

与任何其他PHP静态变量一样,静态属性只能是 使用文本或常量初始化;不允许使用表达式。 因此,虽然可以将静态属性初始化为整数或数组 (例如),您不能将其初始化为另一个变量,即 函数返回值,或返回到对象

我将属性初始化为
null
,使用访问器方法将其设置为私有,并让访问器在第一次调用它时进行“真正”的初始化。下面是一个例子:

    class myclass {

        private static $blah2 = null;

        public static function blah2() {
            if (self::$blah2 == null) {
               self::$blah2 = array( new myotherclass(),
                 new myotherclass(),
                 new myotherclass());
            }
            return self::$blah2;
        }
    }

    print_r(myclass::blah2());

虽然您无法初始化它以获得这些值,但可以调用静态方法将它们推送到它自己的内部集合中,正如我在下面所做的那样。这可能是你能得到的最接近的

class foo {
  public $bar = "fizzbuzz";
}

class myClass {
  static public $array = array();
  static public function init() {
    while ( count( self::$array ) < 3 )
      array_push( self::$array, new foo() );
  }
}

myClass::init();
print_r( myClass::$array );
class-foo{
public$bar=“fizzbuzz”;
}
类myClass{
静态公共$array=array();
静态公共函数init(){
while(count(self::$array)<3)
array_push(self:$array,new foo());
}
}
myClass::init();
打印(myClass::$array);
演示:

这将导致以下输出:

Array ( [0] => foo Object ( [bar] => fizzbuzz ) [1] => foo Object ( [bar] => fizzbuzz ) [2] => foo Object ( [bar] => fizzbuzz ) ) 排列 ( [0]=>foo对象 ( [吧台]=>嘶嘶作响 ) [1] =>foo对象 ( [吧台]=>嘶嘶作响 ) [2] =>foo对象 ( [吧台]=>嘶嘶作响 )
)您能告诉我们错误是在构造函数中设置的吗。您不能在属性定义中设置运行时计算值。@Wiseguy我没有弄错您的消息吗?@Wiseguy:OP需要一个静态数组-每个类一个。每次创建新实例时都初始化它似乎是一种糟糕的方法。@user1181950:在一个不相关的注释中,通过引用使用
new
已经贬值了好几年了。也许它被PHP忽略了,这就是为什么它至今仍然没有导致致命错误的原因。但是,正如你所知。