Home >Backend Development >PHP Tutorial >How Can I Properly Initialize Complex Static Variables in PHP?

How Can I Properly Initialize Complex Static Variables in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-27 17:44:11851browse

How Can I Properly Initialize Complex Static Variables in PHP?

Initializing Static Variables in PHP

When initializing static variables in PHP, you may encounter syntax errors with non-trivial expressions in the initializer, as seen in the code snippet below:

private static $dates = array(
  'start' => mktime( 0,  0,  0,  7, 30, 2009),  // Start date
  'end'   => mktime( 0,  0,  0,  8,  2, 2009),  // End date
  'close' => mktime(23, 59, 59,  7, 20, 2009),  // Date when registration closes
  'early' => mktime( 0,  0,  0,  3, 19, 2009),  // Date when early bird discount ends
);

Workaround:

One solution is to avoid complex expressions in the initializer and instead assign the values after defining the class:

class Foo {
  static $bar;
}
Foo::$bar = array(…);

Another option is to use a static function to initialize the variable:

class Foo {
  private static $bar;
  static function init()
  {
    self::$bar = array(…);
  }
}
Foo::init();

PHP 5.6 Improvement:

PHP 5.6 supports some expressions in static variable initializers. For example, you can define an abstract class with a private static function to initialize the variable:

abstract class Foo{
    private static function bar(){
        static $bar = null;
        if ($bar == null)
            bar = array(...);
        return $bar;
    }
    /* use where necessary */
    self::bar();
}

The above is the detailed content of How Can I Properly Initialize Complex Static Variables in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn