Class Abstraction 之间有什么区别?和一个 Object Interfaces在 PHP 中?我问是因为,我真的不明白他们两个有什么意义,他们都做同样的事情!那么,两者结合使用的缺点有哪些优势呢?
类抽象:
abstract class aClass
{
// Force extending class to define these methods
abstract public function setVariable($name, $var);
abstract public function getHtml($template);
}
对象接口(interface):
interface iClass
{
// Force impementing class to define these methods
public function setVariable($name, $var);
public function getHtml($template);
}
最佳答案
您可以实现多个接口(interface),但只能扩展一个类。
可能:
class MyClass extends MyAbstract implements MyInterface1, MyInterface2, MyInterface3 { }
不可能:
class MyClass extends MyAbstract1, MyAbstract2 implements MyInterface { }
此外,接口(interface)不能有实现。
可能:
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 - Damien 关于接口(interface)如何成为契约的观点很重要。
关于php - PHP 中类抽象和对象接口(interface)的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3018909/