Home  >  Article  >  Backend Development  >  Comprehensive understanding of static keywords

Comprehensive understanding of static keywords

小云云
小云云Original
2018-03-08 09:12:281737browse


The static keyword means static or global, and can be used to modify classes, methods and variables. Usually we hear about class members or static variables (that is, they will not change after loading). When a static member is loaded, it will not change. For example, a String string will not change its value once it is initialized. Generally in development, we modify shared members with static.

1. The most common ones are: used to modify member variables (turn them into members of the class), e.g.: program status and exception information. (These two are usually modified together with static and final, which is very common in development).

2. Used to modify member methods and turn them into class methods, which can be called using "type.method name", often used in tool classes. (That is, there is no need to create objects)

3. Static code block, put multiple objects together to initialize (static code block is executed earlier, only after static variables)

static Variables

Next let’s talk about the difference between static variables (modified by static) and instance variables (not modified by static variables):

1. Static variables: just a copy in memory, It is only initialized once, memory is allocated only once, and can be accessed directly using the type or by creating an object.

2. Instance variable: When called, an object needs to be created. Memory must be allocated once before it is created. There can be multiple exams in the memory, but they do not affect each other.

Static method

Static methods can be called directly through the class name, and instances can also be called directly. Therefore, the super and this keywords cannot exist in static methods (wouldn't it be the same as being a rogue if they did? Instance variables are associated with specific objects).

Related recommendations:

Detailed explanation of the use of static keyword in PHP

What are the differences between new self() and new static() Difference

Detailed explanation of the difference between static and self in php

The above is the detailed content of Comprehensive understanding of static keywords. 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