可能重复:
引用子类的静态成员
请看一下下面的代码来理解我的问题。
<?php
Interface IDoesSomething
{
public static function returnSomething();
}
abstract class MiddleManClass implements IDoesSomething
{
public static function doSomething()
{
return 1337 * self::returnSomething();
}
}
class SomeClass extends MiddleManClass
{
public static function returnSomething()
{
return 999;
}
}
// and now, the vicious call
$foo = SomeClass::doSomething();
/**
* results in a
* PHP Fatal error: Cannot call abstract method IDoesSomething::returnSomething()
*/
?>
有没有一种方法可以强制抽象returnSomething()
,同时保持从抽象"中间人"类中定义的函数调用函数的可能性?对我来说,这似乎是PHP的一个瓶颈。
如果php版本>=5.3,则更改
public static function doSomething()
{
return 1337 * self::returnSomething();
}
至
public static function doSomething()
{
return 1337 * static::returnSomething();
}
为什么要使用statics,它不是很好的OOP?Statics不适合用于继承,因为它们旨在为该类提供专门的功能。这正是你所需要的。
<?php
Interface IDoesSomething{
public function returnSomething();
}
abstract class MiddleManClass implements IDoesSomething{
public function doSomething(){
return 1337 * $this->returnSomething();
}
}
class SomeClass extends MiddleManClass{
public function returnSomething(){
return 999;
}
}
$someClass = new SomeClass();
$foo = $someClass->doSomething();
这个问题被称为"后期静态绑定":php手动