Home  >  Article  >  Backend Development  >  Detailed examples of how to use PHP interface technology to implement simple polymorphic applications

Detailed examples of how to use PHP interface technology to implement simple polymorphic applications

伊谢尔伦
伊谢尔伦Original
2017-06-29 10:11:311088browse

Introduces PHP to realize simple polymorphic applications based on interface technology, and analyzes the definition of PHP interface, inheritance, calling and polymorphic related implementation skills in combination with complete examples. Friends can refer to the following

<?php
//实现多态的一个简单实例
interface USB{
  //接口中的方法权限必须是public,并且只有抽象方法或常量
  function mount();
  function work();
  function unmount();
}
class Upan implements USB{
  function mount(){
    echo "U盘被成功挂载!!<br>";
  }
  function work(){
    echo "U盘正在工作……<br>";
  }
  function unmount(){
    echo "U盘被成功卸载!!<br>";
  }
}
class ShuBiao implements USB{
  function mount(){
    echo "USB鼠标被成功插入!<br>";
  }
  function work(){
    echo "USB鼠标正在工作……<br>";
  }
  function unmount(){
    echo "USB鼠标被成功拔除!<br>";
  }
}
class DianNao{
  function useUSB($usb){    //这就是一种多态,当传进去的参数为不同的usb设备时,调用不同设备的相同的方法名,但产生了不同的效果
    $usb->mount();
    $usb->work();
    $usb->unmount();
  }
}
class Worker{
  function install(){
    $dn=new DianNao;  //激活电脑
    $up=new Upan;    //激活优盘
    $sb=new ShuBiao;  //激活鼠标
    $dn->useUSB($up);  //电脑访问优盘
    $dn->useUSB($sb);  //电脑访问鼠标
  }
}
$usb_user=new Worker;  //激活一个USB设备的使用者
$usb_user->install();  //使用者调用安装USB设备的方法
?>

example operation effect:

The above is the detailed content of Detailed examples of how to use PHP interface technology to implement simple polymorphic applications. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn