Home  >  Article  >  Backend Development  >  Detailed explanation of static member variables and non-static member variables in PHP

Detailed explanation of static member variables and non-static member variables in PHP

墨辰丷
墨辰丷Original
2018-05-25 14:45:321387browse

Data members can be divided into static variables and non-static variables. This article mainly introduces PHP static member variables and non-static member variables. Friends in need can refer to it

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

Static members:Members in a static class are static members by adding the static modifier. You can directly use the class name static member name to access this static member. Because static members exist in memory, non-static members need to be instantiated before memory is allocated, so static members cannot access non-static members. Because static members exist in memory, non-static members can directly access static members in the class.

Non-static members: All members that are not static are non-static members. When the class is instantiated, it can be accessed through the instantiated class name. Survival of non-static members The lifetime is determined by the lifetime of the class. There is no concept of lifetime for static members, because static members always reside in the content.

A class can also contain static members and non-static members , classes also include static constructors and non-static constructors..
can be summarized in two aspects. The first aspect is mainly relative to process orientation, that is, classes are not involved in this aspect. The second aspect is relatively For object-oriented, it mainly explains the role of static in the class.

1. The static keyword in process-oriented design

1. Static global variables

Definition: Add the keyword static before the global variable, and the variable is defined as a static global variable.

Features:

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

B. Initialization: If not explicitly initialized, it will be implicitly initialized to 0 (automatic variables are random unless explicitly initialized).

C. Access variables are only visible in the source file. Strictly speaking, they should start from the point of definition and end in this file.

例(摘于C++程序设计教程---钱能主编P103):         //file1.cpp 
        //Example 1
       #include 
       void fn();
        static int n; //定义静态全局变量
        void main()
        {
    n=20;
    cout<    fn();
        }
        void fn()
        {
    n++;
    cout<        }

D. Const constants declared in the file scope default to static storage type.

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

Generally, the dynamic data generated by new in the program is stored in the heap area, and the dynamic data inside the function is stored in the heap area. Automatic variables are stored in the stack area. Automatic variables generally release 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 will not release space when the function exits. Careful readers may find that in the code in Example 1,

                     static int n; //Define static global variables

is changed to:

int n ; //Define global variables

The program will still run normally. Indeed, by defining global variables, variables can be shared in files, but defining static global variables also has the following benefits:

  • Static global variables cannot be used by other files; (It seems to be the difference extern)

  • Variables with the same name can be defined in other files without conflict;

You can change the above example code to As follows:

//Example 2
//File1
#include 
void fn();
static int n; //定义静态全局变量(只能在本文件中使用)
void main()
{
 n=20;
 cout<
extern int n;(可在别的文件中引用这个变量)
void fn()
{
 n++;
 cout<

Compile and run Example 2, you will find that the above codes can be compiled separately, but an error occurs during linking. Try changing
static int n; //Define static global variables

to

int n; //Define global variables

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

2. Static local variables

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

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<

Usually, a variable is defined in the function body, and whenever the program When this statement is executed, stack memory will be allocated to the local variable. But as the program exits the function body, the system will reclaim the stack memory and local variables will become invalid accordingly.

But sometimes we need to save the value of a variable between calls. The usual idea is to define a global variable to do this. But in this way, the variables no longer belong to the function itself and are no longer only controlled by the function, which brings inconvenience to the maintenance of the program.

Static local variables can solve this problem. Static local variables are saved in the global data area instead of on the stack. Each value is kept until the next call until a new value is assigned next time.

Features:

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

B. Initialization: If not explicitly initialized, it will be implicitly initialized to 0, and subsequent function calls will no longer be initialized.

  C、它始终驻留在全局数据区,直到程序运行结束。但其作用域为局部作用域,当定义它的函数或 语句块结束时,其作用域随之结束。

3、静态函数(注意与类的静态成员函数区别)

定义:在函数的返回类型前加上static关键字,函数即被定义成静态函数。

特点:

  A、静态函数与普通函数不同,它只能在声明它的文件当中可见,不能被其它文件使用。   

静态函数的例子:

//Example 4
#include 
static void fn();//声明静态函数
void main()
{
 fn();
}
void fn()//定义静态函数
{
 int n=10;
 cout<

定义静态函数的好处:

  • 静态函数不能被其它文件所用;

  • 其它文件中可以定义相同名字的函数,不会发生冲突;

二、面向对象的static关键字(类中的static关键字)

1、静态数据成员

在类内数据成员的声明前加上关键字static,该数据成员就是类内的静态数据成员。先举一个静态数据成员的例子。

//Example 5
#include 
class Myclass
{
public:
 Myclass(int a,int b,int c);
 void GetSum();
private:
 int a,b,c;
 static int Sum;//声明静态数据成员
};
int Myclass::Sum=0;//定义并初始化静态数据成员

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="<

可以看出,静态数据成员有以下特点:

  • 对于非静态数据成员,每个类对象都有自己的拷贝。而静态数据成员被当作是类的成员。无论这个类的对象被定义了多少个,静态数据成员在程序中也只有一份拷贝,由该类型的所有对象共享访问。也就是说,静态数据成员是该类的所有对象所共有的。对该类的多个对象来说,静态数据成员只分配一次内存,供所有对象共用。所以,静态数据成员的值对每个对象都是一样的,它的值可以更新;

  • 静态数据成员存储在全局数据区。静态数据成员定义时要分配空间,所以不能在类声明中定义。在Example 5中,语句int Myclass::Sum=0;是定义静态数据成员;

  • 静态数据成员和普通数据成员一样遵从public,protected,private访问规则;

  • 因为静态数据成员在全局数据区分配内存,属于本类的所有对象共享,所以,它不属于特定的类对象,在没有产生类对象时其作用域就可见,即在没有产生类的实例时,我们就可以操作它;

  • 静态数据成员初始化与一般数据成员初始化不同。静态数据成员初始化的格式为:

  • <数据类型><类名>::<静态数据成员名>=<值>

  • 类的静态数据成员有两种访问形式:

  • <类对象名>.<静态数据成员名> 或 <类类型名>::<静态数据成员名>

  • 如果静态数据成员的访问权限允许的话(即public的成员),可在程序中,按上述格式来引用静态数据成员 ;

  • 静态数据成员主要用在各个对象都有相同的某项属性的时候。比如对于一个存款类,每个实例的利息都是相同的。所以,应该把利息设为存款类的静态数据成员。这有两个好处,第一,不管定义多少个存款类对象,利息数据成员都共享分配在全局数据区的内存,所以节省存储空间。第二,一旦利息需要改变时,只要改变一次,则所有存款类对象的利息全改变过来了;

  • 同全局变量相比,使用静态数据成员有两个优势:

静态数据成员没有进入程序的全局名字空间,因此不存在与程序中其它全局名字冲突的可能性;

可以实现信息隐藏。静态数据成员可以是private成员,而全局变量不能;

2、静态成员函数

  与静态数据成员一样,我们也可以创建一个静态成员函数,它为类的全部服务而不是为某一个类的具体对象服务。静态成员函数与静态数据成员一样,都是类的内部实现,属于类定义的一部分。普通的成员函数一般都隐含了一个this指针,this指针指向类的对象本身,因为普通成员函数总是具体的属于某个类的具体对象的。通常情况下,this是缺省的。如函数fn()实际上是this->fn()。但是与普通函数相比,静态成员函数由于不是与任何的对象相联系,因此它不具有this指针。从这个意义上讲,它无法访问属于类对象的非静态数据成员,也无法访问非静态成员函数,它只能调用其余的静态成员函数。下面举个静态成员函数的例子。

//Example 6
#include 
class Myclass
{
public:
 Myclass(int a,int b,int c);
 static void GetSum();/声明静态成员函数
private:
 int a,b,c;
 static int Sum;//声明静态数据成员
};
int Myclass::Sum=0;//定义并初始化静态数据成员
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<

Static members of a class are different from general class members: static members have nothing to do with the instance of the object, only the class itself. They are used to implement the functions and data that the class wants to encapsulate, but do not include the functions and data of specific objects. Static members include static methods and static properties.

Static properties contain data to be encapsulated in a class and can be shared by all instances of the class. In fact, in addition to belonging to a fixed class and restricting access methods, the static properties of a class are very similar to the global variables of a function.

Static methods implement functions that need to be encapsulated by the class and have nothing to do with specific objects. Static methods are very similar to global functions. Static methods can fully access the properties of the class, or they can be accessed by instances of the object, regardless of access What is the qualifier of .

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!

Ordinary methods are called with ->. PHP will create a this variable. Static methods do not belong to any object. In some cases, we even want to call it when there is no valid object, then Static methods should be used. PHP will not create this variable inside static methods, even if you call them from an object.

You can write a method to show whether it is called statically or non-statically by determining whether this is created. Of course, if you use the static keyword, this method will always be static no matter how it is called. of.

Your class can also define constant attributes. You don’t need to use public static, just use the const keyword. Constant attributes are always static. They are attributes of the class, not the instantiation of the class. properties of the object.

The problem of efficiency between PHP static methods and non-static methods

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

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

The above is the entire content of this article, I hope it will be helpful to everyone's study.


Related recommendations:

Using jsVariablesBugs encountered in scope

Variables and function promotion steps in JS

PHP learning: predefinedVariablesDetails

The above is the detailed content of Detailed explanation of static member variables and non-static member variables in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn