Home  >  Article  >  Backend Development  >  How to Properly Initialize Static Variables in PHP?

How to Properly Initialize Static Variables in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-25 05:04:12256browse

How to Properly Initialize Static Variables in PHP?

Initializing Static Variables in PHP: A Guide

Problem:

You encounter an error while initializing static variables in PHP code using the syntax private static $dates = array(...);. Specifically, you receive a "syntax error" related to unexpected parentheses.

Answer:

In PHP, complex expressions cannot be used directly in static variable initializers. Here are two methods to work around this limitation:

Method 1: Using Class Initialization Code

After defining the class, add the following code:

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

Method 2: Using a Static Initialization Method

Define a static initialization method and call it manually:

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

PHP 5.6 :

In PHP 5.6 and later, you can use limited expressions in static variable initializers. However, for complex expressions, the above methods may still be necessary. For abstract classes, the following syntax can be used:

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 to 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