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

Detailed explanation of PHP new static and new self

高洛峰
Release: 2023-03-05 21:54:01
Original
1234 people have browsed it

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
Copy after login

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 这里
 }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template