Home > Article > Backend Development > The difference between new self() and new static in PHP object-oriented
First clarify the conclusion. In PHP, self points to the class that defines the currently called method, and static points to the class that calls the current static method.
The following is an example to prove the above result
class A { public static $_a = 'Class A'; public static function echoProperty() { echo self::$_a . PHP_EOL; } } class B extends A { public static $_a = 'Class B'; } $obj = new B(); B::echoProperty();//输出 ‘Class A
The reason why this is the case is because using self:: or __CLASS__ to statically refer to the current class depends on the class in which the called method is defined. The above Class A The method echoProperty is modified to become:
class A { public static $_a = 'Class A'; public static function echoProperty() { echo static::$_a . PHP_EOL; } } //再次调用B::echoProperty将输出 'CLASS B'
In order to avoid the subclass seen in the first example above overwriting the static properties of the parent class, using the inherited method to still access the static properties of the parent class, PHP5. 3 Added a new syntax: Late static binding, using the static keyword instead of the self keyword, so that static points to the same class returned by get_called_class(), that is, the class currently calling the static method. This key Words are also valid for access to static methods.
The following example better illustrates the difference between new self() and new static() (the latter uses PHP's late static binding to point to the current class of the calling method)
class A { public static function get_self() { return new self(); } public static function get_static() { return new static(); } } class B extends A {} echo get_class(B::get_self()); // A echo get_class(B::get_static()); // B echo get_class(A::get_self()); // A echo get_class(A::get_static()); // A