Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - define static array of objects

Tags:

arrays

object

php

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?

like image 959
user1181950 Avatar asked May 27 '12 03:05

user1181950


People also ask

Can you have an array of objects in PHP?

Yes, its possible to have array of objects in PHP. Do we have to go on incrementing the constructor index in myObject() each time we want to add a new object in the array or is it optional? All this OOP stuff in web languages is simply OOPS!

How do you call an array of objects in PHP?

If it is called an array or object depends on the outermost part of your variable. So [new StdClass] is an array even if it has (nested) objects inside of it and $object->property = array(); is an object even if it has (nested) arrays inside. And if you are not sure if you have an object or array, just use gettype() .

What is static array in 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.

How can we define static variable in PHP?

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.


1 Answers

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 initialize the property to null, make it private with an accessor method, and have the accessor do the "real" initialization the first time it's called. Here's an 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()); 
like image 131
Mark Reed Avatar answered Sep 18 '22 13:09

Mark Reed