php - 接口(interface)的使用

标签 php oop interface

来自 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/

相关文章:

php - mysql SELECT WHERE 查询在 elseif 循环内不执行任何操作并且没有错误

php - Laravel,ajax 发布后更新字段

php - 如何动态加载php代码并检查类是否实现接口(interface)

c++ - 存在内存泄漏问题的链表

java - android fragment 接口(interface)nullpointerexception

C# 和 ReSharper : Checking an object's type

php - 网页内容未通过 json 函数(数据)更新

php - PayPal Express Checkout 即时更新未更新运费

java - 在基类中结合 fragment 和 Activity 类

c# - OOP 中的默认参数是不好的做法吗?