php中的抽象和界面有什么区别?

Fly*_*Cat 6 php oop abstract-class interface class

可能重复:
PHP:接口和抽象类之间有什么区别?

嗨,大家好..

据我所知,一个clase实现或扩展abstract或接口类必须使用默认方法.我知道我们可以使用implement关键字来使用多个接口,但我们只能扩展1个抽象.任何人都可以解释在现实生活中使用哪一个项目和区别?太感谢了!!!!

Pis*_*3.0 11

差异既有理论上的,也有实际的:

  • interface是对您的类具有的一些功能的描述和广告(因此实现相同接口的各种类可以以相同的方式使用)
  • abstract class可以是一个默认实现,包含可能出现在所有实现中的部分.它不必实现完整的接口

示例 - 界面:

// define what any class implementing this must be capable of
interface IRetrieveData {
    // retrieve the resource
    function fetch($url);

    // get the result of the retrieval (true on success, false otherwise)
    function getOperationResult();

    // what is this class called?
    function getMyClassName();
}
Run Code Online (Sandbox Code Playgroud)

现在我们已经为每个实现此功能的类检查了一系列需求.让我们创建一个抽象类及其子类:

// define default behavior for the children of this class
abstract class AbstractRetriever implements IRetrieveData {
    protected $result = false;

    // define here, so we don't need to define this in every implementation
    function getResult() {
       return $result;
    }

    // note we're not implementing the other two methods,
    // as this will be very different for each class.
}

class CurlRetriever extends AbstractRetriever {
     function fetch($url) {
         // (setup, config etc...)
         $out = curl_execute();
         $this->result = !(curl_error());
         return $out;
     }
     function getMyClassName() {
         return 'CurlRetriever is my name!';
     }
}

class PhpRetriever extends AbstractRetriever {
     function fetch($url) {
        $out = file_get_contents($url);
        $this->result = ($out !== FALSE);
        return $out;
     }
     function getMyClassName() {
         return 'PhpRetriever';
     }
}
Run Code Online (Sandbox Code Playgroud)

一个完全不同的抽象类(与接口无关),带有实现我们接口的子类:

abstract class AbstractDog {
     function bark() {
         return 'Woof!'; 
     }
}

class GoldenRetriever extends AbstractDog implements IRetrieveData {
     // this class has a completely different implementation
     // than AbstractRetriever
     // so it doesn't make sense to extend AbstractRetriever
     // however, we need to implement all the methods of the interface
     private $hasFetched = false;

     function getResult() {
         return $this->hasFetched;
     }

     function fetch($url) {
         // (some retrieval code etc...)
         $this->hasFetched = true;
         return $response;
     }
     function getMyClassName() {
         return parent::bark();
     }
}
Run Code Online (Sandbox Code Playgroud)

现在,在其他代码中,我们可以这样做:

function getStuff(IRetrieveData $retriever, $url) {
    $stuff = $retriever->fetch($url);
}
Run Code Online (Sandbox Code Playgroud)

我们不必担心将传入哪些检索器(cURL,PHP或Golden),以及它们如何实现目标,因为所有检索器都应该具有相似的行为.您也可以使用抽象类来完成此操作,但是您根据类的祖先而不是其功能来限制自己.


hay*_*uhl 6

多重与单一继承:

  • 您只能从单个抽象类继承
  • 您可以实现多个接口

执行:

  • 抽象类实际上可以包含有效的代码.这使您可以在子类之间共享实现
  • 接口仅定义公共成员函数.实现相同接口的类实际上不共享代码.

这就是我所知道的.