Quantcast
Channel: How to initialize static variables - Stack Overflow
Viewing all articles
Browse latest Browse all 11

Answer by David Luhman for How to initialize static variables

$
0
0

Here is a hopefully helpful pointer, in a code example. Note how the initializer function is only called once.

Also, if you invert the calls to StaticClass::initializeStStateArr() and $st = new StaticClass() you'll get the same result.

$ cat static.php<?phpclass StaticClass {  public static  $stStateArr = NULL;  public function __construct() {    if (!isset(self::$stStateArr)) {      self::initializeStStateArr();    }  }  public static function initializeStStateArr() {    if (!isset(self::$stStateArr)) {      self::$stStateArr = array('CA' => 'California', 'CO' => 'Colorado',);      echo "In " . __FUNCTION__. "\n";    }  }}print "Starting...\n";StaticClass::initializeStStateArr();$st = new StaticClass();print_r (StaticClass::$stStateArr);

Which yields :

$ php static.phpStarting...In initializeStStateArrArray(    [CA] => California    [CO] => Colorado)

Viewing all articles
Browse latest Browse all 11

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>