Home  >  Article  >  Backend Development  >  Detailed explanation of PHP new static and new self

Detailed explanation of PHP new static and new self

高洛峰
高洛峰Original
2017-02-21 15:29:431151browse

Use self:: or __CLASS__ to statically refer 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:

PHP new static 和 new self详解

For more detailed explanations of PHP new static and new self, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn