PHP new static and new self, staticself
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:
Happy Hacking