我想知道当静态子类扩展静态父类时,使用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()之间有什么区别吗?如果有,那是什么呢?
谢谢
问候
发布于 2014-01-03 00:27:07
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中使用单例模式时,self并不支持子类,而static支持New self vs. new static
parent提供了访问继承的类方法的能力,如果您需要保留一些默认功能,这通常很有用。
发布于 2014-01-03 00:49:48
self用于调用静态函数和操纵静态变量,这些变量是类特定的,而不是对象特定的。
https://stackoverflow.com/questions/20886911
复制相似问题