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

How Can I Properly Initialize Static Variables in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-29 03:32:09452browse

How Can I Properly Initialize Static Variables in PHP?

Initializing Static Variables in PHP

When initializing static variables, you may encounter syntax errors like the one exemplified in the given code snippet. This is because PHP cannot parse complex expressions within the variable initializer.

Alternative Initialization Methods

To resolve this issue, consider using the following alternative methods:

  • Separate Initialization: Define your static variable as usual, then initialize it using a separate statement outside of the class definition.
class Registration {
  static $dates;
}
Registration::$dates = array(
  'start' => mktime(0, 0, 0, 7, 30, 2009),
  'end' => mktime(0, 0, 0, 8, 2, 2009),
  'close' => mktime(23, 59, 59, 7, 20, 2009),
  'early' => mktime(0, 0, 0, 3, 19, 2009),
);
  • Initialization Function: Create a static function within the class to handle the initialization.
class Registration {
  private static $dates;

  static function init() {
    self::$dates = array(
      'start' => mktime(0, 0, 0, 7, 30, 2009),
      'end' => mktime(0, 0, 0, 8, 2, 2009),
      'close' => mktime(23, 59, 59, 7, 20, 2009),
      'early' => mktime(0, 0, 0, 3, 19, 2009),
    );
  }

  // Call the init function to initialize the variable
  public function __construct() {
    static::init();
  }
}

PHP 5.6 Support

PHP 5.6 introduced limited support for non-trivial expressions in static variable initializers. However, it is recommended to use the aforementioned methods for clarity and compatibility with earlier versions of PHP.

The above is the detailed content of How Can I Properly Initialize 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