php -- new self() 和 new static

时间:2023-03-09 05:38:20
php -- new self() 和 new static

看一段摘自网上的代码

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_static()); // A

通俗点讲就是:

new self();   在哪个类里面执行的该代码,返回的就是哪个类的对象。如果该代码只写在父类中,即使子类继承自父类,返回的依然是父类的对象。

new static();  哪个类调用的它,返回的就是哪个类的的对象。