A brief analysis of the concepts and differences between abstract classes and interfaces in php

  • 2020-06-22 23:57:38
  • OfStack


// Definition of abstract class: 
abstract class ku{  // define 1 An abstract class 
  abstract function kx();
  ......
}
function aa extends ku{
  // Methods that implement abstract classes 
  function kx(){
    echo 'sdsf';
  }
}
// Method of use 
$aa=new aa;
$aa->kx();
//1. define 1 Subclasses must fully implement all methods in this abstraction 
//2. You cannot create an object from an abstract class; its point is to be extended 
//3. Abstract classes usually have abstract methods without curly braces 
//4. Abstract methods do not have to implement concrete functions; they are done by subclasses 
//5. When a subclass implements a method of an abstract class, the visibility of its subclass must be greater than or equal to the definition of the abstract method 
//6. Methods of an abstract class can have arguments or be empty 
//7. If an abstract method has arguments, then an implementation of a subclass must have the same number of arguments 
////////////////////////////// Definition of interface class: 
interface Shop{
      public   function buy($gid);
      public   function sell($gid);
      abstract function view($gid);
}
// If you want to use an interface, you must define all the methods in the interface class 1 None of them ( abstract Except). 
// In this way, if 1 In a large project, no matter how someone else does the following method, he must implement all the methods in this interface !
// Example: implement the above interface 1 methods 
class BaseShop implements Shop{
   public function buy($gid){
      echo ' You have purchased ID for  :' . $gid . ' The goods ';
   }
   public function sell($gid){
      echo ' Do you buy for ID for  :' . $gid . ' The goods ';
   }
   public function view($gid){
      echo ' You are browsing ID for  :' . $gid . ' The goods ';
   }
}
// Examples of multiple inheritance of interfaces: 
<?php
interface staff_i1{ // interface 1
  function setID();
  function getID();
}
interface staff_i2{ // interface 2
  function setName();
  function getName();
}
class staff implements staff_i1,staff_i2{
  private $id;
  private $name;
  function setID($id){
    $this->id = $id;
  }
  function getID(){
    return $this->id;
  }
  function setName($name){
    $this->name = $name;
  }
  function getName(){
    return $this->name;
  }
  function otherFunc(){ // This is a 1 Methods that do not exist in an interface 
    echo  " Test " ;
  }
}
?>

Their differences:
1. Abstract classes can have non-abstract methods and interfaces can only have abstract methods!
2. A class can inherit from multiple interfaces, while a class can only inherit from one abstract class!
3. Interfaces are used via the implements keyword, while abstract classes are used via inheritance via the extends keyword!

Related articles: