PHP static member variables and non-static member variables. php static _ PHP Tutorial

Source: Internet
Author: User
PHP static member variables and non-static member variables, php static. PHP static member variables and non-static member variables. php static data members can be divided into static variables and non-static variables. static Member: the static modifier is added to the members of the static class, that is, PHP static member variables and non-static member variables.

Data members can be divided into static variables and non-static variables.
Static member: a member in a static class is added with a static modifier, which is a static member. you can directly use the class name + static member name to access this static member. because the static member exists in the memory, non-static members need to be instantiated to allocate the memory, so static members cannot access non-static members .. because static members exist in the memory, non-static members can directly access static members in the class.

Non-Static member: all non-Static members are non-Static members. after the class is instantiated, it can be accessed by the instantiated class name .. the lifetime of a non-static member is determined by the lifetime of the class .. static members do not have the concept of survival, because static members always reside in the content ..

A class can also contain static and non-static members. The class also includes static constructors and non-static constructors ..

It is summarized in two aspects: the first is relative to the process-oriented, that is, the class is not involved in this aspect, and the second is relative to the object-oriented, it mainly describes the role of static in the class.

I. static keywords in process-oriented design

1. static global variables

Definition: before a global variable, add the keyword "static". the variable is defined as a static global variable.

Features:
A. The variable allocates memory in the global data zone.
B. initialization: if explicit initialization is not performed, the value 0 is implicitly initialized (automatic variables are random unless explicitly initialized ).
C. The access variable is only visible in the source file. Strictly speaking, it should be defined from the beginning to the end of this file.

Example (from the C ++ Programming Tutorial --- Qian Neng, editor of P103): // file1.cpp
// Example 1
# Include
Void fn ();
Static int n; // defines the static global variable.
Void main ()
{
N = 20;
Cout < Fn ();
}

Void fn ()
{
N ++;
Cout < }

D. The constant declared in the file scope is static storage by default.

All static variables are allocated memory in the global data zone, including the static local variables to be mentioned later. For a complete program, the distribution in the memory is as follows:
 

Code area
Global Data Zone
Heap area
Stack zone

In general, dynamic data generated by new is stored in the heap zone, and automatic variables in the function are stored in the stack zone. Automatic variables usually release space as the function exits, and static data (even static local variables in the function) is stored in the global data zone. The data in the global data zone does not release space because the function exits. Careful readers may find that

Static int n; // defines the static global variable.

Changed:

Int n; // defines the global variable

The program runs normally. Indeed, defining global variables can share variables in files, but defining static global variables has the following benefits:

  • Static global variables cannot be used by other files; (it seems to be different from extern)
  • Variables with the same name can be defined in other files without conflict;

You can change the sample code as follows:

// Example 2 // File1 # include
 
  
Void fn (); static int n; // defines static global variables (only available in this file) void main () {n = 20; cout <
  
   
Extern int n; (this variable can be referenced in other files) void fn () {n ++; cout <
   
    
Compile and run Example 2, and you will find that the above code can be compiled separately, but an error occurs during link. Try
Static int n; // defines the static global variable.
Change
Int n; // defines the global variable
Compile and run the program again to understand the differences between global variables and static global variables.


2. static local variables

Definition: When the static keyword is added before a local variable, the static local variable is defined.

Here is an example of static local variables:

// Example 3 # include
     
      
Void fn (); void main () {fn ();} void fn () {static n = 10; cout <
      
       
Generally, a variable is defined in the function body, and stack memory is allocated to the local variable whenever the program runs the statement. However, as the program exits from the function body, the system will reclaim the stack memory and the local variables will also become invalid.
But sometimes we need to save the variable value between two calls. The general idea is to define a global variable for implementation. In this way, the variable no longer belongs to the function itself, and is no longer only controlled by the function, causing inconvenience to program maintenance.
Static local variables can solve this problem. Static local variables are stored in the global data zone, instead of in the stack. each value is kept to the next call until the next value is assigned.

Features:
A. The variable allocates memory in the global data zone.
B. initialization: if explicit initialization is not performed, the value 0 will be implicitly initialized, and subsequent function calls will not be initialized.
C. it always resides in the global data zone until the program is running. But its scope is local scope. when the function or statement block defining it ends, its scope ends.

3. static functions (note the differences between static member functions and classes)

Definition: add the static keyword before the return type of the function. the function is defined as a static function.

Features:
A. static functions are different from common functions. they can only be seen in the files declared for them and cannot be used by other files.
  
Example of static functions:
// Example 4 # include
        
         
Static void fn (); // declare the static function void main () {fn ();} void fn () // define the static function {int n = 10; cout <
         
          
Benefits of defining static functions:
  • Static functions cannot be used by other files;
  • Functions with the same name can be defined in other files without conflict;

2. object-oriented static keywords (static keywords in the class)

1. static data Member

Add the keyword static before the declaration of the data member in the class. The data member is the static data member in the class. Here is an example of a static data member.

// Example 5 # include
           
            
Class Myclass {public: Myclass (int a, int B, int c); void GetSum (); private: int a, B, c; static int Sum; // declare static data member}; int Myclass: Sum = 0; // define and initialize static data member 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 =" <
            
             

It can be seen that static data members have the following features:

  • For non-static data members, each class object has its own copy. Static data members are treated as class members. No matter how many objects are defined for this class, static data members also have only one copy in the program, which is shared by all objects of this type. That is to say, static data members are shared by all objects in the class. For multiple objects in this class, static data members only allocate memory once for all objects to share. Therefore, the values of static data members are the same for each object, and their values can be updated;
  • Static data members are stored in the global data zone. Space must be allocated when defining static data members, so they cannot be defined in the class declaration. In Example 5, the statement int Myclass: Sum = 0 is a member that defines static data;
  • Static data members follow the public, protected, and private access rules like common data members;
  • Because static data members allocate memory in the global data zone and all objects in this class are shared, they do not belong to a specific class object and are visible in the scope when no class object is generated, that is, when no class instance is generated, we can operate on it;
  • Static data member initialization is different from general data member initialization. The static data member initialization format is:
    <Data type> <class name >:< static data member name >=< value>
  • Static data members of a class can be accessed in two forms:
    <Class object name>. <static data member name> or <class type name >:< static data member name>
    If the access permission of the static data member is allowed (that is, the public member), you can reference the static data member in the program in the above format;
  • Static data members are mainly used when each object has the same attribute. For example, for a deposit type, the interest of each instance is the same. Therefore, the interest should be set as the static data member of the deposit class. There are two advantages: first, no matter how many deposit-type objects are defined, interest data members share the memory allocated to the global data area, thus saving storage space. Second, once the interest needs to be changed, the interest of all deposit objects will be changed once;
  • Compared with global variables, static data members have two advantages:

2. static member functions

Like static data members, we can also create a static member function that serves all the classes rather than specific objects of a class. Static member functions, like static data members, are internal implementation of the class and are part of the class definition. A common member function generally implies a this pointer, which points to the object itself of the class, because a common member function always belongs to a specific object of a class. Generally, this is the default value. For example, the function fn () is actually this-> fn (). However, compared with common functions, static member functions do not have the this pointer because they are not associated with any objects. In this sense, it cannot access non-static data members of Class objects or non-static member functions. it can only call other static member functions. The following is an example of a static member function.

// Example 6 # include
              
               
Class Myclass {public: Myclass (int a, int B, int c); static void GetSum ();/declare static member functions private: int a, B, c; static int Sum; // declare static data member}; int Myclass: Sum = 0; // define and initialize 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 <
               

Static member functions can be summarized as follows:

  • The keyword static cannot be specified for function definitions that appear in external classes;
  • Static members can access each other, including static member functions Accessing static data members and accessing static member functions;
  • Non-static member functions can access static member functions and static data members at will;
  • Static member functions cannot access non-static member functions and non-static data members;
  • Without the additional overhead of this pointer, static member functions increase slightly compared with global functions of the class;
  • Call static member functions. you can use the member access operators (.) and (->) to call static member functions for a class object or a pointer to a class object;

Static members of a class are different from general class members: static members are irrelevant to the instance of the object and only related to the class itself. They are used to implement the functions and data to be encapsulated by classes, but do not include the functions and data of specific objects. static members include static methods and static attributes.

Static attributes include the data to be encapsulated in the class, which can be shared by all instances of the class. In fact, apart from being a fixed class and restricting access methods,The static attributes of the class are very similar to the global variables of the function.

Static methods implement the functions that the class needs to encapsulate and have nothing to do with specific objects.Static methods are very similar to global functions.Static methods can be completely accessed by the Category attributes or by the instance of the object, regardless of whether the access qualifier is.

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

Use-> to call a common method. PHP creates a variable named this. the static method does not belong to any object. in some cases, if we want to call a valid object even if it does not exist, we should use static methods. PHP will not create this variable within the static method, even if you call them from an object.

You can write a method to determine whether this is created to show whether it is called statically or not. of course, if you use the static keyword, no matter how it is called, this method is always static.

Your class can also define constant attributes, without using public static, you only need to use the const keyword. constant attributes are always static. they are the attributes of the class, rather than the attributes of the objects of the class.

Efficiency of PHP static and non-static methods

1. the access efficiency of static members is not necessarily higher than that of non-static members;
2. you only need to call the return value of a class method. it is more reasonable to use a static method, otherwise there will be additional overhead due to new.

The data member can be divided into two types: static variables and non-static variables. static members: the members in the static class are added with the static modifier, that is...

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: info-contact@alibabacloud.com 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.