Mar*_*lin 7 php oop abstract-class interface
PHP中的类抽象和对象接口有什么区别?我问,因为,我并没有真正看到他们两个人的意思,他们都做同样的事情!那么,使用两者之间的劣势有什么优势呢?
班级抽象:
abstract class aClass
{
// Force extending class to define these methods
abstract public function setVariable($name, $var);
abstract public function getHtml($template);
}
Run Code Online (Sandbox Code Playgroud)
对象接口:
interface iClass
{
// Force impementing class to define these methods
public function setVariable($name, $var);
public function getHtml($template);
}
Run Code Online (Sandbox Code Playgroud)
Ric*_*uen 20
您可以实现多个接口,但只能扩展一个类.
class MyClass extends MyAbstract implements MyInterface1, MyInterface2, MyInterface3 { }
Run Code Online (Sandbox Code Playgroud)
class MyClass extends MyAbstract1, MyAbstract2 implements MyInterface { }
Run Code Online (Sandbox Code Playgroud)
此外,接口无法实现.
abstract class MyClass {
function doSomething() {
echo "I can give this method an implementation as this is an abstract class";
}
}
Run Code Online (Sandbox Code Playgroud)
interface MyClass {
function doSomething() {
echo "I can NOT give this method an implementation as this is an interface";
}
}
Run Code Online (Sandbox Code Playgroud)
来自Java词汇表:
界面允许某人从头开始实现您的界面或在其他原始或主要用途与您的界面完全不同的其他代码中实现您的界面.对他们而言,您的界面只是偶然的,必须添加到他们的代码才能使用您的包.
相比之下,抽象类提供了更多结构.它通常定义一些默认实现,并提供一些对完整实现有用的工具.问题是,使用它的代码必须使用您的类作为基础.如果其他想要使用您的包的程序员已经独立开发了自己的类层次结构,那么这可能非常不方便.在Java中,类只能从一个基类继承.
你还应该看看这个问题 - 达米恩关于界面如何成为合同的观点是一个重要问题.