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.
We use a static property Counter::$count in the following example. It belongs to the Counter class and not to any instance of Counter. You cannot use this to refer to it, but you can use self or other valid naming expressions. In the example, the getCount method returns self::$count, not Counter::$count.
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 toglobal functions. Static methods can fully access the attributes of the class, or they can also be accessed by the object's instance to access, regardless of the access qualifier.
In the previous example, getCount is an ordinary method, called with ->. PHP creates a this variable, although the method is not used .However, getCount does not belong to any object. In some cases, we even want to call it when there is no valid object, then a static method should be used. PHP will not establish this variable inside the static method, even if you call it from an object Call them.
Example 6.7 comes from 6.3 changing getCount to a static method.Static keywordcannot prevent an instance from calling getCount using the ->operator. But PHP will not create this variable inside the method. If you use this-> to call, an error will occur.
//6.3 Example refers to Section 4--ConstructorandDestructorExamples (see the previous article), through comparison of the two examples, you can have a good grasp of the difference between
//static methods and ordinary methods.
You 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.
Your class can also define constant attributes. You don’t need to use public static, just use theconst keyword. Constant attributes are always static. They are attributes of the class, not instantiations of the class. Attributes of the object.
Listing 6.7 Static members
##
The above is the detailed content of In-depth analysis of static members of PHP classes. For more information, please follow other related articles on the PHP Chinese website!