PHP – how to initialize static variables

Sometimes we need to populate static variables in php (e.g. populating associative arrays from existing arrays). Easiest way is to define a static function (e.g. init()) and then call it statically after the class.

class Foo {
  static $a = ["foo", "bar"];
  static $aa = array();
  static function init () {
    foreach (self::$a as $val) {
      self::$aa[$val] = 1;
    [foo] => 1
    [bar] => 1
Env: PHP 5.5.9 (Linux)

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments