是的,PHP中的静态方法可以被继承。
在PHP中,静态方法属于类本身,而不是类的实例。当一个类继承另一个类时,子类会继承父类的所有公共(public
)和受保护(protected
)的静态方法。子类可以直接调用这些静态方法,也可以选择重写(override)这些静态方法。
class ParentClass {
public static function staticMethod() {
echo "Static method in ParentClass\n";
}
}
class ChildClass extends ParentClass {
// 可以选择重写父类的静态方法
public static function staticMethod() {
echo "Static method in ChildClass\n";
}
}
// 调用父类的静态方法
ParentClass::staticMethod(); // 输出: Static method in ParentClass
// 调用子类的静态方法
ChildClass::staticMethod(); // 输出: Static method in ChildClass
// 如果子类没有重写静态方法,调用的是父类的静态方法
class AnotherChildClass extends ParentClass {
// 没有重写 staticMethod
}
AnotherChildClass::staticMethod(); // 输出: Static method in ParentClass
self::
或 static::
来调用。self::
会调用当前类的静态方法,而 static::
会调用实际运行时的类的静态方法(考虑继承关系)。class ParentClass {
public static function who() {
echo __CLASS__ . "\n";
}
public static function test() {
self::who(); // 调用当前类的静态方法
static::who(); // 调用实际运行时的类的静态方法
}
}
class ChildClass extends ParentClass {
public static function who() {
echo __CLASS__ . "\n";
}
}
ParentClass::test(); // 输出: ParentClass ParentClass
ChildClass::test(); // 输出: ParentClass ChildClass
在这个例子中,self::who()
总是调用 ParentClass
的 who()
方法,而 static::who()
会根据实际调用的类来决定调用哪个 who()
方法。
总结:PHP中的静态方法可以被继承,并且子类可以选择重写这些静态方法。