Home > Article > Backend Development > php static variable initialization code example
What is staticstatic variable?
Static variable The type specifier is static.
Static variables belong to static storage, and their storage space is the static data area in the memory (storage units are allocated in the static storage area). The data in this area occupies these storage spaces throughout the running of the program. (It is not released during the entire running of the program), and it can also be considered that its memory address remains unchanged until the end of the entire program (on the contrary, auto automatic variables, that is, dynamic local variables, belong to the dynamic storage category and occupy dynamic storage space, FunctionIt will be released after the call is completed). Although static variables always exist throughout the execution of the program, they cannot be used outside its scope.
In addition, variables belonging to the static storage method are not necessarily static variables. For example: Although external variables (referred to as global variables in PHP) are static storage methods, they are not necessarily static variables. They must be defined by static before they can become static external variables, or static global variables.
All global variables are static variables, and local variables are local static variables only when they are defined with the type modifier static.
Static variables can be applied anywhere. Once the application is successful, it will no longer accept other similar applications.
Static variables do not mean that they cannot change the value. The amount that cannot change the value is called a constant. The value it holds is mutable, and it will remain up-to-date. It is said to be static because it will not change as the function is called and exits. That is, if we assign a certain value to a static variable the last time the function is called, the value will remain unchanged the next time the function is called.
Members of phpVariables can be initialized at the same time as they are declared, but they can only be initialized with scalars. For example:
class A {
public $f1 = 'xxxx';
static public $f2 = 100;
}
If you want to assign a variable to an
, you can only initialize it in the constructor, for example:
class A { private $child; public function construct() { $this->child = new B(); } }
constructor/static block in php in php, so there is no appropriate time to initialize it. There are ways to solve the problem for shared members, for example:
class A { static public $child; } A::$child = new B();
class A { static private $child; static public initialize() { self::$child = new B(); } } A::initialize();
The above is the detailed content of php static variable initialization code example. For more information, please follow other related articles on the PHP Chinese website!