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

How Can I Properly Initialize Static Variables with Complex Expressions in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-11-20 00:37:03892browse

How Can I Properly Initialize Static Variables with Complex Expressions in PHP?

Initialization of Static Variables in PHP

PHP presents a challenge when initializing static variables due to its inability to evaluate non-trivial expressions within initializers. Consider the following code:

private static $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),  
);

This code triggers a parse error because PHP expects a ")" after the assignment operator, as seen in the following error message:

Parse error: syntax error, unexpected '(', expecting ')' in /home/user/Sites/site/registration/inc/registration.class.inc on line 19

To circumvent this limitation, we can employ alternative approaches:

1. Deferred Initialization

After defining the class, we can initialize the static variable explicitly using a separate block of code:

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

2. Static Initialization Method

We can define a static method within the class to initialize the variable:

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

Note: PHP 5.6 introduced support for certain expressions in static variable initializers, but this functionality is limited.

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