PHP - 定义对象的静态数组

2022-08-30 15:19:16

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

class myclass {
    public static $blah = array("test1", "test2", "test3");
}

但是当我这样做时

class myclass {
    public static $blah2 = array(
        &new myotherclass(),
        &new myotherclass(),
        &new myotherclass()
    );
}

其中 myother 类定义在 my 类的正上方。然而,这会产生一个错误;有没有办法实现它?


答案 1

不。从 http://php.net/manual/en/language.oop5.static.php

像任何其他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());

答案 2

虽然您无法将其初始化为具有这些值,但可以调用静态方法将它们推送到其自己的内部集合中,就像我在下面所做的那样。这可能与您将获得的一样接近。

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 );

演示:http://codepad.org/InTPdUCT

这将产生以下输出:

Array
(
  [0] => foo Object
    (
      [bar] => fizzbuzz
    )
  [1] => foo Object
    (
      [bar] => fizzbuzz
    )
  [2] => foo Object
    (
      [bar] => fizzbuzz
    )
)