SoFunction
Updated on 2025-03-02

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


//Definition of abstract class:
abstract class ku{  //Define an abstract class
  abstract function kx();
  ......
}
function aa extends ku{
//Methods to implement abstract classes
  function kx(){
    echo 'sdsf';
  }
}
//How to use
$aa=new aa;
$aa->kx();
//1. Define some methods, and the subclass must fully implement all methods in this abstraction.
//2. Objects cannot be created from abstract classes, its meaning is to be extended
//3. Abstract classes usually have abstract methods, without braces in the methods
//4. Abstract methods do not need to implement specific functions, they are completed by subclasses.
//5. When a subclass implements an abstract class method, the visibility of its subclass must be greater than or equal to the definition of the abstract method.
//6. The method of an abstract class can have parameters or be empty
//7. If the abstract method has parameters, the implementation of the subclass must also have the same number of parameters.
//////////////////////////////////////////////// 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 the interface class so that no less methods are allowed (except abstract).
//In this way, if you do the following methods in a big project, no matter how others do it, it must implement all the methods in this interface!
//Example: A method to implement the above interface
class BaseShop implements Shop{
   public function buy($gid){
echo 'You purchased the item with the ID :' . $gid . ';
   }
   public function sell($gid){
echo 'You buy and sell products with ID :' . $gid . ';
   }
   public function view($gid){
echo 'You have browsed the product with ID :' . $gid . ';
   }
}
// Multiple inheritance example of interface:
<?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 method that does not exist in an interface
    echo “Test”;
  }
}
?>