Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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", "test3");
}

but when I do

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

where myotherclass is defined right above myclass. That throws an error however; is there a way to achieve it?

share|improve this question
    
Could you tell us that the error is? –  xbonez May 27 '12 at 3:52
3  
Set $blah2 within the constructor. You can't set runtime-calculated values in a property definition. –  Wiseguy May 27 '12 at 3:56
    
@Wiseguy did I get your message right? –  Brett May 27 '12 at 4:10
    
@wiseguy: OP wants a static array - one per class. Initializing it every time you create a new instance seems like a bad approach.. –  Mark Reed May 27 '12 at 4:10
    
@user1181950: on an unrelated note, using new by reference there has been depreciated for several years now. Maybe it's slipped under PHP's radar and that's why it still remains to this day without causing a fatal error. But, just so you know. –  bob-the-destroyer May 27 '12 at 4:16

3 Answers 3

up vote 9 down vote accepted

Nope. From http://php.net/manual/en/language.oop5.static.php:

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

I would write an accessor method that returns the value of the property, and have it initialize it the first time it's called.

ETA Example:

    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());
share|improve this answer
1  
Thanks for the prompt reply –  user1181950 May 27 '12 at 4:11
    
Now I get it. Nice one man. Thanks for helping me learn. –  Brett May 27 '12 at 4:20
    
yup, I ended up doing that. thanks again. –  user1181950 May 27 '12 at 6: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
    )
)
share|improve this answer

Per wiseguys comment this is what you need to do:

class myclass 
{
    static $blah2;

    private function initBlah2()
    {
       $this->blah2 = array(&new myotherclass(), &new myotherclass(), &new myotherclass());
    }
}

The problem with your code is that you are trying to dynamically create the values during initialisation. Do it in the constructor instead.

I think this is what wiseguy is saying.

share|improve this answer
1  
Shouldn't it be $this->blah2? –  Filype May 27 '12 at 4:05
1  
OP wants a static value - one per class. Initializing it every time you create a new instance seems like a bad approach. –  Mark Reed May 27 '12 at 4:09
1  
@brett: you're still initializing blah2 during instance creation; since it's a static member, it's available even if there are no instances at all, in which case it never gets initialized. The problem is, there's no static equivalent of a constructor in which to do such initialization, so you have to use a different contract with your client code. You can require that they call a function once (like Jonathan Sampson's init method), but my approach was instead not to expose the value as a property, but a method. The first time it's called, it initializes the (private) property. –  Mark Reed May 27 '12 at 4:22
1  
@brett: actually, that should be self::$blah2 = .... Otherwise, it emits a strict accessing static via non-static method error, and creates a duplicate $blah2 object property. In other words, the static property is not altered with $this->blah2 = .... –  bob-the-destroyer May 27 '12 at 4:23
1  
Thanks @MarkReed, when I read your answer above I began to get what you were saying. This has helped solidify it. I love how answering people's questions helps me learn. Thanks again Mark. –  Brett May 27 '12 at 4:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.