来自 an earlier question 的澄清关于 OO PHP。我已经在 php.net 网站上查看过,但仍不能完全确定。应该是一个快速的答案,我希望。
在接口(interface)中“定义”方法时,实现它的类必须使用 全部 接口(interface)中列出的方法?
例子:
interface foo {
public function blah();
public function de();
public function bleh();
}
class bar implements foo {
public function blah() {
//Code here
}
public function bleh() {
//More code here
}
}
那行得通吗?
最佳答案
没有。实现 interface 的类必须实现接口(interface)定义的所有方法或被定义为抽象的。如果您尝试在未定义所有方法的情况下运行脚本,您将得到
Fatal error: Class bar contains 1 abstract method and must therefore be declared abstract or implement the remaining methods
换句话说,要么做
abstract class bar implements foo {}
或者
abstract class bar implements foo {
public function blah() { /* code */ }
public function bleh() { /* code */ }
}
或者在具体类中保留一些方法为空
class bar implements foo {
public function blah() { /* code */ }
public function bleh() { /* code */ }
public function de() {}
}
关于php - 接口(interface)的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3550287/