Analysis on the Function and Usage of Static (Static) Keyword in PHP

  • 2021-12-04 18:26:00
  • OfStack

This paper illustrates the function and usage of Static (static) keyword in PHP. Share it for your reference, as follows:

1. What is static?

static is a commonly used modifier in C + +, which is used to control the storage and visibility of variables. However, in PHP, the static keyword is used to define static methods and properties, and can also be used to define static variables and later static bindings.

2. Why introduce static?

A variable defined inside a function, when the program executes to its definition, the compiler allocates space on the stack for it. As we all know, the space allocated by the function on the stack will be released at the end of the execution of this function, which raises a question: If you want to save the value of this variable in the function until the next call, how to realize it? The easiest way to think of is to define a global variable, but defining it as a global variable has many disadvantages, the most obvious of which is to destroy the access scope of this variable (so that the variables defined in this function are not only controlled by this function).

3. When will static be used?

A data object is required to serve the whole class instead of an object, and at the same time, it strives not to destroy the encapsulation of the class, that is, it requires this member to be hidden inside the class and invisible to the outside world.

4. Internal mechanism of static:

Static data members must exist for Program 1 to start running. Because functions are called while the program is running, static data members cannot allocate space and initialize within any function.

In this way, its space allocation has three possible places, 1 is the header file as the external interface of the class, where there is the class declaration; 2 is the internal implementation of the class definition, where there is the member function definition of the class; 3 is the global data declaration and definition before the main () function of the application.

Static data members actually allocate space, so they cannot be defined in the declaration of a class (only data members can be declared). The class declaration only declares the "size and specification" of one class, and does not make actual memory allocation, so it is wrong to write as a definition in the class declaration. Nor can it be defined externally in the header file of the class declaration, because that would result in duplicate definitions of the class in multiple source files that use it.

static was introduced to tell the compiler to store variables in the program's static storage area instead of on-stack space, initialize static data members in the order in which they appear as defined, and ensure that the nested members are initialized when nesting static members. The order of elimination is the reverse order of initialization.

5. Advantages of static:

Memory is saved because it is common to all objects, so for multiple objects, static data members are stored in only 1 place for all objects to share. The value of a static data member is 1 for each object, but its value can be updated. As long as the value of static data members is updated once, all objects are guaranteed to access the same value after updating, which can improve time efficiency.

6. When referring to static data members, use the following format:

<类名>::<静态成员名>

Static data members can be referenced in the program in the above format if their access permissions allow (that is, members of public)

7. Precautions:

(1) The static member function of a class is an object that belongs to the whole class rather than the class, so it has no this pointer, which leads to its only access to the static data and static member functions of the class. The pseudo-variable $this is not available in static methods because they can be called without an object. Static properties cannot be passed by objects- > Operator to access. Calling a non-static method statically causes an E_STRICT level error. (2) Static member functions cannot be defined as virtual functions. (3) Because static members are declared in the class and operate outside it, it is somewhat special to take addresses for them. The variable address is a pointer to its data type, and the function address type is an "nonmember function pointer". (4) Because the static member function has no this pointer, it is almost equivalent to the nonmember function. As a result, it has an unexpected benefit: becoming an callback function, which enables us to combine C + + with C-ES62X Window system and successfully apply it to thread functions. (5) static does not increase the time and space overhead of the program, on the contrary, it also shortens the access time of subclasses to static members of the parent class and saves the memory space of subclasses. (6) Static data members in the < Definition or description > When preceded by the keyword static. (7) The static data member is statically stored, so it must be initialized. (8) Static member initialization is different from generic data member initialization:

Initialization is performed outside the class without static, so as not to be confused with 1 static variable or object;
When initializing, the access control symbols private, public, etc. of the member are not added;
When initializing, use scope operator to indicate the class to which it belongs;
So we get the format of static data member initialization:
< Data type > < Class name > :: < Static data member name > = < Value >

(9) In order to prevent the influence of the parent class, a static variable that is the same as the parent class can be defined in the subclass to shield the influence of the parent class. There is one point to note here: We say that static members are shared by parents and children, but we have defined static members repeatedly. Will this cause errors? No, our compiler uses a wonderful technique: name-mangling to generate only 1 flags.

8. Practice

Examples of static properties and methods


<?php
class Foo
{
  public static $my_static = 'foo';
  public function staticValue() {
    return self::$my_static;
  }
  public static function output() {
    return self::$my_static;
  }
}
class Bar extends Foo
{
  public function fooStatic() {
    return parent::$my_static;
  }
}
print Foo::$my_static . "\n";
print Foo::output() . "\n";
$foo = new Foo();
print $foo->staticValue() . "\n";
print $foo->my_static . "\n";   // Undefined "Property" my_static
print $foo::$my_static . "\n";

Examples of static variables


<?php
function Test()
{
  $a = 0;
  echo $a;
  $a++;
}
?>

This function is useless because it sets the value of $a to 0 and outputs 0 on each call. Adding 1 to the variable $a + + has no effect, because once 1 exits this function, the variable $a will not exist. To write a count function that does not lose the current count value, define the variable $a as static:


<?php
function test()
{
  static $a = 0;
  echo $a;
  $a++;
}
?>

Now, the variable $a is initialized only on the first call to the test () function, and each subsequent call to the test () function outputs the value of $a plus 1.

Static variables also provide a way to deal with recursive functions. A recursive function is a function that calls itself. Be careful when writing recursive functions, because it may go on infinitely recursively. You must ensure that there are sufficient methods to abort recursion. The following simple function recursively counts to 10, using the static variable $count to determine when to stop:


<?php
function test()
{
  static $count = 0;
  $count++;
  echo $count;
  if ($count < 10) {
    test();
  }
  $count--;
}
?>

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Syntax", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: