Use self:: or __CLASS__ to make a static reference to the current class, depending on the class in which the current method is defined: using static:: is no longer parsed to the class in which the current method is defined, but is calculated at actual runtime. . It can also be called "static binding" because it can be used for (but is not limited to) calls to static methods.
I was recently asked a small question in the comments of a video: Are there any special considerations when choosing to use static instead of self here? Or we can change the question like this:
What are the specific new static and new self of PHP?
In fact, it should be very clear if we look at an example:
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()); // Father echo get_class(Son::getStatic()); // Son echo get_class(Father::getSelf()); // Father echo get_class(Father::getStatic()); // Father
Pay attention to this line hereget_class(Son::getStatic());
The class Son
is returned, which can be summarized as follows:
new self
1.self
returns the class where the keyword new
in new self
is located, such as Here's an example:
public static function getSelf() { return new self(); // new 关键字在 Father 这里 }
always returns Father
.
new static
2.static
Based on the above, it is a little smarter: static
will return to execute new static( )
class, such as Son
execute get_class(Son::getStatic())
returns Son
, Father
execute get_class(Father::getStatic())
returns Father
and in the absence of inheritance, it can be considered that new self
and new static
returns the same result.
Tips: You can use a good IDE to read comments directly. For example, PhpStorm:
The above is the entire content of this article, I hope it will be helpful to everyone's learning.
Related recommendations:
Analysis of the difference between new self() and new static() in PHP
The use of self and this in PHP
This self in PHP The difference between static
The above is the detailed content of Detailed explanation of PHP new static and new self. For more information, please follow other related articles on the PHP Chinese website!