当前位置:网站首页>[PHP] PHP interface inheritance and interface multi inheritance principle and implementation method

[PHP] PHP interface inheritance and interface multi inheritance principle and implementation method

2022-07-07 16:36:00 weixin_ forty-three million two hundred and twenty-four thousan

stay PHP The interface of , Interface can inherit interface . although PHP Class can only inherit one parent class ( Single inheritance ), But interfaces and classes are different , Interfaces can implement multiple inheritance , You can inherit one or more interfaces . Of course, interface inheritance also uses extends keyword , If you want more than one inheritance, just separate the inherited interfaces with commas .

It should be noted that when your interface inherits other interfaces , Directly inherit the static constant properties and abstract methods of the parent interface , So when a class implements an interface, it must implement all the relevant abstract methods .

Now you are right PHP Have you understood the inheritance of interfaces , The following examples are for reference , The code is as follows

<?php
interface father{
  function shuchu();
}
interface fam extends father{
  function cook($name);
}
class test implements fam{
  function shuchu(){
    echo " Interface inheritance , To implement two abstract methods ";
    echo "<br>";
  }
  function cook($name){
    echo " People who usually cook are :".$name;
  }
}
$t=new test();
$t->shuchu();
$t->cook(" Mom ");
?>

result :
Interface inheritance , To implement two abstract methods
People who usually cook are : Mom

The above example is that the interface inherits an interface , So in test Class implementation fam Two abstract methods should be instantiated in the interface , It is to instance the abstract methods of the subclass and parent of the interface .

Let's take a look at an example of interface multi inheritance , The code is as follows :

<?php
interface father{
  function shuchu();
}
interface mother{
  function dayin($my);
}
interface fam extends father,mother{
  function cook($name);
}
class test implements fam{
  function dayin($my){
    echo " My name is :".$my;
    echo "<br>";
  }
  function shuchu(){
    echo " Interface inheritance , To implement two abstract methods ";
    echo "<br>";
  }
  function cook($name){
    echo " People who usually cook are :".$name;
  }
}
$t=new test();
$t->shuchu();
$t->dayin(" cockroach ");
$t->cook(" Mom ");
?>

result :
Interface inheritance , To implement two abstract methods
My name is : cockroach
People who usually cook are : Mom

原网站

版权声明
本文为[weixin_ forty-three million two hundred and twenty-four thousan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071416475297.html