This article is a detailed analysis and introduction to the concepts and differences between abstract classes and interfaces in PHP. Friends in need can refer to it.
Copy code The code is as follows:
//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. Subclasses must fully implement all methods in this abstraction
//2. Objects cannot be created from abstract classes, their meaning is to be extended
//3. Abstract classes usually have abstract methods, and there are no curly brackets
in the methods
//4. Abstract methods do not have to implement specific functions, and are completed by subclasses
//5. When a subclass implements a method of an abstract class, the visibility of the subclass must be greater than or equal to the definition of the abstract method
//6. Methods of abstract classes can have parameters or be empty
//7. If the abstract method has parameters, then the implementation of the subclass must also have the same number of parameters
////////////////////////////////Interface class definition:
interface Shop{
public function buy($gid);
public function sell($gid);
abstract function view($gid);
}
//If you want to use an interface, you must define any method in the interface class (except abstract).
//In this way, if in a large project, no matter how others do the following method, they 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 product with the ID:' . $gid . '';
}
public function sell($gid){
echo 'You purchased the product with the ID:' . $gid . '';
}
public function view($gid){
echo 'You browsed the product with ID:' . $gid . '';
}
}
//Multiple inheritance example of interface:
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 the interface
echo “Test”;
}
}
?>
Their differences:
1. Abstract classes can have non-abstract methods, while interfaces can only have abstract methods!
2. A class can inherit multiple interfaces, but a class can only inherit one abstract class!
3. The interface is used through the implements keyword, and the abstract class is used by inheriting the extends keyword!