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 isSon
This class can be summarized as follows:
New self
1.self
The returned result isnew self
Medium keywordnew
In the class, for example:
Public static function getSelf () {return new self (); // The new Keyword is in Father}
Always returnFather
.
New static
2.static
On the basis of the above, it is a little smarter:static
Will return executionnew static()
Class, suchSon
Runget_class(Son::getStatic())
The returned result isSon
,Father
Runget_class(Father::getStatic())
The returned result isFather
In the absence of inheritance, we can consider thatnew self
Andnew static
Returns the same result.
Tips: You can use a good IDE to directly view comments. For example, PhpStorm:
Happy Hacking