Analysis of the function and usage of static keyword in PHP

Time:2020-4-5

This paper introduces the function and usage of static keyword in PHP. To share with you for your reference, as follows:

1. What is static?

Static is a very common modifier in C + +, which is used to control the storage and visibility of variables. However, in PHP, static keyword is used to define static methods and properties. It can also be used to define static variables and late static binding.

2. Why static?

When a program executes to its definition, the compiler allocates space on the stack for the variable defined inside the function. As we all know, the space allocated on the stack will be released at the end of the function execution, so a problem arises: if you want to save the value of this variable in the function to the next call, how to implement it? The easiest way to think of is to define a global variable, but there are many disadvantages in defining a global variable. The most obvious disadvantage is that it destroys the access range of this variable (so that the variables defined in this function are not only controlled by this function).

3. When do you use static?

A data object is needed to serve the whole class rather than an object, and at the same time, the encapsulation of the class should not be broken. That is to say, this member should be hidden inside the class and invisible to the outside.

4. Internal mechanism of static:

Static data members must exist at the beginning of a program. Because a function is 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: first, as the header file of the external interface of the class, there are class declarations; second, the internal implementation of the class definition, there are class member function definitions; third, the global data declarations and definitions before the main() function of the application program.

Static data members need to actually allocate space, so they cannot be defined in the declaration of a class (only data members can be declared). Class declaration only declares the “size and specification” of a class and does not make actual memory allocation, so it is wrong to write a definition in the class declaration. It also cannot define the external definition of the class declaration in the header file, because that will cause it to be defined repeatedly in multiple source files using the class.

Static is introduced to inform the compiler that variables are stored in the static storage area of the program instead of the stack space. Static data members are initialized in the order in which they appear. Note that when static members are nested, the nested members must be initialized. The order of elimination is the reverse of initialization.

5. Advantages of static:

Memory can be saved because it is public to all objects, so for multiple objects, static data members only store one place for all objects to share. The value of a static data member is the same for each object, but its value can be updated. As long as the values of static data members are updated once, all objects can access the same updated values, which can improve the time efficiency.

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

< class name >: < static member name >

If the access rights of static data members allow (i.e. members of public), the static data members can be referenced in the program according to the above format

7. Precautions:

  • (1) The static member function of a class belongs to the whole class rather than the object of the class, so it has no this pointer, which results in that it can only access the static data and static member function of the class. Because static methods do not need to be called through objects, the dummy variable $this is not available in static methods. Static properties cannot be accessed by objects through the – > operator. Calling a non static method statically can result in an e ﹣ strict level error.
  • (2) A static member function cannot be defined as a virtual function.
  • (3) Because the static member is declared in the class and operated outside of it, the address operation is somewhat special. The variable address is a pointer to its data type, and the function address type is a “non member function pointer”.
  • (4) Because the static member function has no this pointer, it is almost equivalent to the non member function. As a result, it has an unexpected advantage: it becomes a callback function, which enables us to combine C + + with C-based X window system, and at the same time, it is successfully applied to the line function.
  • (5) Static does not increase the time and space cost of the program. Instead, it shortens the access time of the subclass to the static members of the parent class and saves the memory space of the subclass.
  • (6) Static data members are prefixed with the keyword static when they are < definition or description >.
  • (7) Static data members are stored statically, so they must be initialized.
  • (8) Static member initialization is different from general data member initialization:

    Initialization is performed outside the class without static in front of it to avoid confusion with general static variables or objects;
    During initialization, access control characters such as private and public are not added;
    The scope operator is used to indicate its class during initialization;
    So we get the format of static data member initialization:
    < data type > < class name >: < static data member name > = < value >

  • (9) To prevent the influence of the parent class, you can define a static variable in the child class that is the same as the parent class to shield the influence of the parent class. Here’s one thing to note: we say that static members are shared by parent and child classes, but we have defined static members repeatedly, will this cause errors? No, our compiler uses a wonderful technique: name mangling to generate unique 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 of no use because each call sets the value of $a to 0 and outputs 0. Adding one variable to $a + + has no effect, because once you exit this function, the variable $a does 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 the first time the test() function is called, after which each time the test() function is called, it will output the value of $a and add one.

Static variables also provide a way to handle recursive functions. A recursive function is a function that calls itself. Be careful when writing recursive functions, because infinite recursion is possible. 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 information about PHP, you can see the following topics: PHP object-oriented programming introduction, PHP array operation skills, PHP basic syntax introduction, PHP operation and operator usage summary, PHP string usage summary, PHP + MySQL database operation introduction and PHP common database operation Skills summary

I hope this article is helpful for PHP programming.