加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP中的类抽象和对象接口之间的区别?

发布时间:2020-12-13 18:26:39 所属栏目:PHP教程 来源:网络整理
导读:PHP中的 Class Abstraction和 Object Interfaces有什么区别?我问,因为,我并没有真正看到他们两个人的意思,他们都做同样的事情!那么,使用两者之间的劣势有什么优势呢? 班级抽象: abstract class aClass{ // Force extending class to define these method
PHP中的 Class Abstraction和 Object Interfaces有什么区别?我问,因为,我并没有真正看到他们两个人的意思,他们都做同样的事情!那么,使用两者之间的劣势有什么优势呢?

班级抽象:

abstract class aClass
{
    // Force extending class to define these methods
    abstract public function setVariable($name,$var);
    abstract public function getHtml($template);
}

对象接口:

interface iClass
{
    // Force impementing class to define these methods
    public function setVariable($name,$var);
    public function getHtml($template);
}
您可以实现多个接口,但只能扩展一个类.

可能:

class MyClass extends MyAbstract implements MyInterface1,MyInterface2,MyInterface3 {  }

不可能:

class MyClass extends MyAbstract1,MyAbstract2 implements MyInterface {  }

此外,接口不能实现.

可能:

abstract class MyClass {
    function doSomething() {
        echo "I can give this method an implementation as this is an abstract class";
    }
}

不可能:

interface MyClass {
    function doSomething() {
        echo "I can NOT give this method an implementation as this is an interface";
    }
}

从Java Glossary:

An interface allows somebody to start from scratch to implement your interface or implement your interface in some other code whose original or primary purpose was quite different from your interface. To them,your interface is only incidental,something that have to add on to the their code to be able to use your package.

An abstract class,in contrast,provides more structure. It usually defines some default implementations and provides some tools useful for a full implementation. The catch is,code using it must use your class as the base. That may be highly inconvenient if the other programmers wanting to use your package have already developed their own class hierarchy independently. In Java,a class can inherit from only one base class.

您还应该看一看this question – 达米恩关于界面如何成为合同的重要观点.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读