我想知道当静态子类扩展静态父类时使用 self::和 parent::有什么区别,例如
class Parent {
public static function foo() {
echo 'foo';
}
}
class Child extends Parent {
public static function func() {
self::foo();
}
public static function func2() {
parent::foo();
}
}
func() 和 func2() 之间有什么区别吗?如果有,那是什么?
谢谢
问候
最佳答案
Child has foo() Parent has foo()
self::foo() YES YES Child foo() is executed
parent::foo() YES YES Parent foo() is executed
self::foo() YES NO Child foo() is executed
parent::foo() YES NO ERROR
self::foo() NO YES Parent foo() is executed
parent::foo() NO YES Parent foo() is executed
self::foo() NO NO ERROR
parent::foo() NO NO ERROR
如果您正在寻找适合他们使用的案例。 parent
允许访问继承的类,而 self
是对运行方法(静态或其他方式)所属类的引用。
self
关键字的一个流行用法是在 PHP 中使用 Singleton 模式时,self
不支持子类,而 static
做 New self vs. new static
parent
提供访问继承类方法的能力,如果您需要保留一些默认功能,这通常很有用。
关于PHP: self::vs parent::with 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20886911/