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

前端之家收集整理的这篇文章主要介绍了PHP中的类抽象和对象接口之间的区别?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
PHP中的 Class AbstractionObject 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 – 达米恩关于界面如何成为合同的重要观点.

原文链接:https://www.f2er.com/php/135839.html

猜你在找的PHP相关文章