Initialize static variables in PHP
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php class MyClass { public static $nums = array(1, 2, 3, 4, 5); } print_r(MyClass::$nums); /* Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php class MyClass { public static $nums; } MyClass::$nums = array(1, 2, 3, 4, 5); print_r(MyClass::$nums); /* Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php class MyClass { private static $nums; public static function initNums($array) { self::$nums = $array; } public static function getNums() { return self::$nums; } } MyClass::initNums(array(1, 2, 3, 4, 5)); print_r(MyClass::getNums()); /* Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) */ ?> |
A better solution is to initialize the static property only once. You can achieve this by doing something like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php class MyClass { private static $nums = null; private static function InitializeAndGetNums() { if (self::$nums === null) { self::$nums = array(1, 2, 3, 4, 5); } return self::$nums; } public static function getNums() { return self::InitializeAndGetNums(); } } print_r(MyClass::getNums()); /* Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) */ ?> |
That’s all about declare and initializing static variables in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)