English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

In-depth Explanation of PHP new static and new self

Recently, in the comments of a video, I was asked a small question: Was there a special consideration for choosing static instead of self here? Or we can rephrase the question like this:

What exactly do PHP's new static and new self do?63;

In fact, looking at an example should make it 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()); // Father
echo get_class(Son::getStatic()); // Son
echo get_class(Father::getSelf()); // Father
echo get_class(Father::getStatic()); // Father

In this line, pay attention to get_class(Son::getStatic()); which returns the class Son, and you can summarize as follows:

new self

1.self returns the class where the keyword new is located in new self, for example, in this example:

public static function getSelf() {
  return new self(); // The new keyword is here in Father
 }

Always returns Father.

new static

2.static is a bit smarter on top of that: static will return the class that executes new static(), for example, Son executing get_class(Son::getStatic()) returns Son, and Father executing get_class(Father::getStatic()) returns Father

In the absence of inheritance, you can consider new self and new static to return the same result.

Tips: You can use a good IDE to view comments directly. For example, PhpStorm:

Happy Hacking

You May Also Like