PHP static member variables and non-static member variables

Source: Internet
Author: User
Data members can be divided into static variables, non-static variables. This article mainly describes the PHP static member variables and non-static member variables, the need for friends can refer to the following

Data members can be divided into static variables, non-static variables, two kinds.

static member: a member in a static class joins the static modifier, which is a statically member. You can access this static member directly using the class name + static member name, because static members exist in memory, non-static members need to be instantiated to allocate memory, so static members cannot access non-static members: Because static members exist in memory, non-static members can access static members of the class directly.

non-static member: all members that do not have static members are nonstatic, and when the class is instantiated, it can be accessed by instantiating the class name. The lifetime of a non-static member is determined by the lifetime of the class. Static members, however, do not have the concept of a lifetime because static members always reside in the content.

You can also include static and non-static members in a class, as well as static constructors and non-static constructors.
Summed up in two ways, the first aspect is mainly relative to the process, that is, in this respect the class is not involved, the second aspect of the object-oriented, the main explanation of the role of static in the class.

I. Static keywords in process-oriented design

1. Static Global variables

Definition: Before a global variable, the variable is defined as a static global variable, plus the keyword static.


A, the variable allocates memory in the global data area.

B, initialization: If it is not explicitly initialized, it is implicitly initialized to 0 (the automatic variable is random unless explicitly initialized).

C, the visit variable only in the source document is visible, strictly speaking should be the definition of the beginning to the end of this document.

Example (excerpt from C + + Programming Tutorial---Money can editor P103)://file1.cpp//example 1       #include        void fn ();        static int n; Defines a static global variable        void main ()        {    n=20;    cout<    fn ();        }        VOID fn ()        {    n++;    cout<        }

D, the Changshime of the const declared under the file scope considers the static storage type.

Static variables allocate memory in the global data area, including the static local variables that will be mentioned later. For a complete program, the distribution in memory is as follows:

The dynamic data generated by new in the general program is stored in the heap area, and the automatic variables inside the function are stored in the stack area. Automatic variables generally free up space as the function exits, and static data (even static local variables inside the function) is stored in the global data area. The data in the global data area does not free up space because of the function's exit. Careful readers may find that the code in Example 1 will

static int n; Defining static global Variables


int n; Defining Global Variables

The program is still functioning normally. It is true that defining global variables allows for the sharing of variables in files, but there are also the following benefits of defining static global variables:

    • Static global variables cannot be used by other files; (as if it were a different extern)

    • Variables of the same name can be defined in other files, and no conflicts will occur;

You can change the example code above to read as follows:

Example 2//file1#include void fn (); static int n; Define a static global variable (only used in this file) void Main () {n=20; cout<extern int n; (this variable can be referenced in another file) void fn () {n++; cout<

Compile and run Example 2 and you will see that the above code can be compiled separately, but there is an error in link. Try to
static int n; Defining static global Variables


int n; Defining Global Variables

Compile and run the program again, carefully understand the difference between global variables and static global variables.

2. Static local Variables

Definition: Static local variables are defined when a local variable is preceded by a static keyword.

Let's first give an example of a static local variable, as follows:

Example 3#include void fn (); void Main () {FN (); FN (); FN ();} VOID fn () {static n=10; cout<

Typically, a variable is defined in the body of the function that allocates stack memory to the local variable whenever the program runs to the statement. However, as the program exits the function body, the system will retract the stack memory, and the local variables are invalidated accordingly.

But sometimes we need to save the values of the variables between the two calls. The usual idea is to define a global variable to implement. In this way, the variables are no longer part of the function itself, and are no longer only controlled by the functions, which inconvenience the maintenance of the program.

Static local variables can solve this problem. Static local variables are saved in the global data area, not in the stack, and each time the value is persisted to the next call until the next time the new value is assigned.


A, the variable allocates memory in the global data area.

B, initialization: If it is not explicitly initialized, it is implicitly initialized to 0, and subsequent function calls are no longer initialized.

C, it always resides in the global data area until the program finishes running. But its scope is a local scope, and when the function or block of statements that defines it ends, its scope ends.

3. Static function (Note the difference from the static member function of the Class)

Definition: With the static keyword preceded by the return type of the function, the function is defined as a static function.


A, the static function differs from the normal function, it can only be seen in the file that declares it, and cannot be used by other files.

Examples of static functions:

Example 4#include static void Fn ();//Declaration of the quiescent function void Main () {FN ();} VOID FN ()//define static function {int n=10; cout<

Benefits of defining static functions:

    • Static functions cannot be used by other files;

    • Other files can define a function of the same name, and no conflict will occur;

Second, the object-oriented static keyword (the static keyword in the Class)

1. Static data members

Precede the declaration of a data member within a class with the keyword static, which is a static data member within the class. Give an example of a static data member first.

Example 5#include class Myclass{public:myclass (int a,int b,int c), void Getsum ();p rivate:int a,b,c, static int sum;//sound Static data members};int myclass::sum=0;//define and initialize static data members
Myclass::myclass (int a,int b,int c) {this->a=a; this->b=b; this->c=c; Sum+=a+b+c;} void Myclass::getsum () {cout<< "sum=" <

As you can see, static data members have the following characteristics:

    • For non-static data members, each class object has its own copy. Static data members are treated as members of the class. Regardless of how many objects of this class are defined, static data members have only one copy in the program and are shared by all objects of that type. In other words, a static data member is common to all objects of that class. For multiple objects of this class, static data members are allocated only once for all objects to be shared. Therefore, the value of a static data member is the same for each object, its value can be updated, and

    • Static data members are stored in the global data area. Static data members are defined when they are allocated space, so they cannot be defined in a class declaration. In Example 5, the statement int myclass::sum=0; is a static data member;

    • Static data members and normal data members comply with PUBLIC,PROTECTED,PRIVATE access rules;

    • Because a static data member allocates memory in the global data area and is shared by all objects of this class, it does not belong to a particular class object, and its scope is visible when no class object is generated, that is, we can manipulate it without producing an instance of the class;

    • Static data member initialization differs from general data member initialization. The static data member is initialized in the format:

    • Type >< class name >::< static data member name >=< value the static data member of the

    • Class has two access forms:

    • Class object name >.< static data member name or class type name >::< static data member name >

    • If the access permission of a static data member is allowed (that is, the member of public), the static data member can be referenced in the program in the above format;

    • Static data members are used primarily when each object has the same property. For example, for a deposit class, the interest is the same for each instance. Therefore, interest should be set as a static data member of the deposit class. There are two benefits, first, regardless of how many deposit class objects are defined, the interest data members share the memory allocated in the global data area, thus saving storage space. Second, once the interest needs to change, as long as the change, the interest of all the deposit class objects has changed;

    • There are two advantages to using static data members over global variables:

Static data members do not enter the program's global namespace, so there is no possibility of conflicts with other global names in the program;

Information hiding can be implemented. A static data member can be a private member, while a global variable cannot;

2. Static member functions

As with static data members, we can also create a static member function that serves the entire service of a class rather than a specific object of a class. Static member functions, like static data members, are internal implementations of the class and are part of the class definition. Ordinary member functions generally imply a this pointer, which points to the object of the class itself, because ordinary member functions are always specific to the specific object of a class. Typically, this is the default. such as the function fn () is actually THIS->FN (). However, compared to a normal function, a static member function does not have the this pointer because it is not associated with any object. In this sense, it cannot access non-static data members that belong to a class object, nor can it access a non-static member function, which only calls the rest of the static member functions. Here is an example of a static member function.

Example 6#include class Myclass{public:myclass (int a,int b,int c), static void Getsum ();/Declaration static member function Private:int a,b,c; St atic int sum;//declares a static data member};int myclass::sum=0;//defines and initializes a static data member myclass::myclass (int a,int b,int c) {this->a=a; this-> B=b; this->c=c; Sum+=a+b+c; Non-static member functions can access static data members}void Myclass::getsum ()///static member function implementation {//cout<

A static member of a class is different from a normal class member: A static member is not related to an instance of an object, but only to the class itself. They are used to implement the functionality and data that the class wants to encapsulate, but do not include features and data for a particular object, static members include static methods and static properties.

A static property contains the data to encapsulate in the class, which can be shared by instances of all classes. In fact, in addition to belonging to a fixed class and restricting access, the static properties of the class are very similar to the global variables of the function.

The static party law implements the functionality that the class needs to encapsulate, regardless of the specific object. A static method is very similar to a global function. A static method can have full access to the properties of a class, or it can be accessed by an instance of an object, regardless of whether the qualifier is accessed.

A class that does not contain any non-static members can be called a static class, and a static class can also be understood as a namespace for global variables and functions!

The normal method is called with. PHP creates a This variable, and the static method does not belong to any object. In some cases, we even want to call it when there are no valid objects, so we should use static methods. PHP will not build this variable inside a static method, even if you call them from an object.

You can write a method by judging whether this is established to show whether it is called statically or statically. Of course, if you use the static keyword, no matter how it is called, this method is always static.

Your class can also define a constant property, and you do not need to use public static, just use the const keyword. Constant properties are always static. They are properties of the class, not the properties of the object that instantiates the class.

The problem of the efficiency of static and non-static methods in PHP

1, static member access efficiency is not necessarily higher than non-static members;

2. It is only necessary to invoke the return value of a method of a class, and it is more reasonable to use static methods, otherwise there will be additional overhead due to new.

Static variables exist only within the scope of the function, and static variables live only on the stack. General function variables are released after the function ends, such as local variables, but static variables do not. The value of the variable is preserved the next time the function is called.

Basic usage of static variables

1. Defining static variables in a class
[Access modifier] static $ variable name;
2. How to access static variables
If there are two methods to access in a class self::$ static variable name, class Name:: $ static variable name
If you are accessing outside the class: There is a method class name:: $ static variable name


Class child{public $name;//This defines and initializes a static variable $nums public static $nums =0; function construct ($name) {$this->name= $name; } public Function Join_game () {//self:: $nums use static variable self:: $nums +=1; Echo $this->name. " Added snowmen game "; }}//Creation of three children $child 1=new child ("Li Kui"); $child 1->join_game (); $child 2=new Child ("Zhang Fei"); $child 2->join_game (); $child 3=new Child ("Tang priest"); $child 3->join_game (); See how many people play the game echo "<br/> have this". Child:: $nums;
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.