Using self: or _ CLASS _ for static reference to the current CLASS depends on the CLASS that defines the current method: using static: is no longer parsed as the CLASS that defines the current method, it is calculated during actual operation. It can also be called "static binding" because it can be used for (but not limited to) calling static methods. Using self: or _ CLASS _ for static reference to the current CLASS depends on the CLASS that defines the current method: using static: is no longer parsed as the CLASS that defines the current method, it is calculated during actual operation. It can also be called "static binding" because it can be used for (but not limited to) calling static methods.
Recently, I was asked a small question in a video comment: Is there any special consideration for static instead of self? Or we can convert the problem as follows:
What are PHP's new static and new self?
In fact, the following example should be clear:
class Father { public static function getSelf() { return new self(); } public static function getStatic() { return new static(); }}class Son extends Father {}echo get_class(Son::getSelf()); // Fatherecho get_class(Son::getStatic()); // Sonecho get_class(Father::getSelf()); // Fatherecho get_class(Father::getStatic()); // Father
Pay attention to this line.get_class(Son::getStatic());The returned result isSonThis class can be summarized as follows:
New self
1.selfThe returned result isnew selfMedium keywordnewIn the class, for example:
Public static function getSelf () {return new self (); // the new keyword is in Father}
Always returnFather.
New static
2.staticOn the basis of the above, it is a little smarter:staticWill return executionnew static()Class, suchSonRunget_class(Son::getStatic())The returned result isSon,FatherRunget_class(Father::getStatic())The returned result isFather
In the absence of inheritance, we can consider thatnew selfAndnew staticReturns the same result.
Tips: you can use a good IDE to directly view comments. For example, PhpStorm:
For more details about PHP new static and new self, please refer to the Chinese PHP website!