Comprehensive understanding of static keywords

小云云
Release: 2023-03-20 21:02:02
Original
1789 people have browsed it


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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template