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
Release: 2024-11-27 17:44:11
Original
783 people have browsed it

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
);
Copy after login

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(…);
Copy after login

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();
Copy after login

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();
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template