Home >Backend Development >PHP Tutorial >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:
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), );
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!