您不能取消定义子函数中的父函数,这不是使用继承的好方法。任何子类都应该能够使用所有父函数。 (否则,为什么还要延长?)
另一种解决方案是仅在每个特定驱动程序中定义您需要的功能,而实用程序仅包含所有驱动程序都可以使用的通用功能(这是最简单的),然后是驱动程序中的驱动程序特定功能。
Class Utility {
public function MethodOne() {
# default MethodOne
}
public function MethodTwo() {
# default MethodTwo
}
}
class Driver extends Utility {
public function MethodThree() {
}
}
class Driver2 extends Utility {
public function MethodFour() {
}
}
这表明 Driver 和 Driver2 具有不同的实现功能,但仍然具有 Utility 中可用的方法。
最终的解决方案(如果您想强制函数位于驱动程序中,否则会引发错误)是实现多个接口,每个接口将一些函数捆绑在一起:
Class Utility {
public function MethodOne() {
print "MethodOne";
}
public function MethodTwo() {
print "MethodTwo";
}
}
interface inter1 {
public function MethodThree();
}
interface inter2 {
public function MethodFour();
}
class Driver extends Utility implements inter1 {
public function MethodThree(){
print "MethodThree";
}
}
class Driver2 extends Utility implements inter2 {
public function MethodFour() {
print "MethodFour";
}
}
两种方案实现的都是一样的,但是Driver必须在接口方案中实现MethodThree:
$d = new Driver();
print "Methods for Driver:\n";
foreach (array("MethodOne","MethodTwo","MethodThree","MethodFour") as $k) {
$p = method_exists($d, $k) ? 'true' : 'false';
print "\t ".$k.": " . $p ."\n";
}
$d = new Driver2();
print "Methods for Driver2:\n";
foreach (array("MethodOne","MethodTwo","MethodThree","MethodFour") as $k) {
$p = method_exists($d, $k) ? 'true' : 'false';
print "\t ".$k.": " . $p ."\n";
}
哪些输出:
Methods for Driver:
MethodOne: true
MethodTwo: true
MethodThree: true
MethodFour: false
Methods for Driver2:
MethodOne: true
MethodTwo: true
MethodThree: false
MethodFour: true
如果你想让 Driver2 有 MethodThree,那么你可以这样写:
class Driver2 extends Utility implements inter2, inter1 {
public function MethodFour() {
print "MethodFour";
}
public function MethodThree() {
}
}