This article demonstrates how to declare and initialize static variables in PHP.

You can declare the class properties as static by adding the static keyword to them. The static properties can be initialized either inside or outside the class and can be accessed using the scope resolution operator (::), as shown below.

Download  Run Code

 
Note how the static properties are accessible without the need for class instantiation. You can even initialize the static property outside the class using the assignment operator, preferably immediately after the class definition.

Download  Run Code

 
For private static properties, you can write utility methods to initialize the static property and return its value from within the class. Note that the static properties can be accessed within the class with self:: syntax.

Download  Run Code

 
A better solution is to initialize the static property only once. You can achieve this by doing something like:

Download  Run Code

That’s all about declare and initializing static variables in PHP.