PHP - define static array of objects

后端 未结 2 1636

can you initialize a static array of objects in a class in PHP? Like you can do

class myclass {
    public static $blah = array(\"test1\", \"test2\", \"test         


        
2条回答
  •  清歌不尽
    2020-12-31 00:17

    While you cannot initialize it to have these values, you can call a static method to push them into its own internal collection, as I've done below. This may be as close as you'll get.

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

    Demo: http://codepad.org/InTPdUCT

    Which results in the following output:

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

提交回复
热议问题