Overview
I am learning design patterns, and I have an article aboutSingleton modeAfter reading this article again, I found that my mastery of static keywords is not very reliable, so I review it again.
static keyword
The introduction of static keywords in the PHP manual is as follows:
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can).
Generally speaking, after declaring the properties and methods of a class as static, you can directly access the static properties and methods without instantiating the object.
The characteristics of static members and methods in PHP are as follows:
1. Static members cannot be accessed through instances of the class, but static methods can.
2. Static members cannot be accessed through the -> operator.
3. In the scope of static methods, the $this keyword cannot appear, that is, ordinary member variables cannot be accessed in static methods.
4. Static members and methods can be accessed directly through class names without instantiating objects.
Late Static Bindings
The following content is excerpted from the PHP manual:
Since PHP 5.3.0, PHP has added a feature called late static binding to refer to static calls in the inheritance scope.
To be precise, the working principle of later static binding is to store the class name of the previous "non-forwarding call". When a static method call is made, the class name is the explicitly specified (usually on the left part of the :: operator); when a non-static method call is made, it is the class to which the object belongs. The so-called "forwarding call" refers to static calls made in the following ways: self::, parent::, static:: and forward_static_call(). The get_called_class() function can be used to get the class name of the called method, and static:: points out its scope.
For understanding this feature, please refer to the following manualexample
self vs static
Use a demo to directly explain the difference between self and static.
Self example:
<?php
class Vehicle {
protected static $name = 'This is a Vehicle';
public static function what_vehicle() {
echo get_called_class()."\n";
echo self::$name;
}
}
class Sedan extends Vehicle {
protected static $name = 'This is a Sedan';
}
Sedan::what_vehicle();
Program output:
Sedan
This is a Vehicle
static example:
<?php
class Vehicle {
protected static $name = 'This is a Vehicle';
public static function what_vehicle() {
echo get_called_class()."\n";
echo static::$name;
}
}
class Sedan extends Vehicle {
protected static $name = 'This is a Sedan';
}
Sedan::what_vehicle();
Program output:
Sedan
This is a Sedan
Summarize
I read the previous article. I haven’t updated my blog for more than a month. Being busy is part of it. The main thing is that I am lazy and I have to persist in the future. This article is a bit unsatisfactory.