Home > Backend Development > PHP Tutorial > PHP method to implement polymorphic applications based on interface technology

PHP method to implement polymorphic applications based on interface technology

墨辰丷
Release: 2023-03-27 17:00:01
Original
1542 people have browsed it

This article mainly introduces PHP to implement simple polymorphic applications based on interface technology. It analyzes the definition, inheritance, calling and polymorphic related implementation techniques of PHP interface in the form of complete examples. Friends in need can refer to it

The example in this article describes the implementation of simple polymorphic applications in PHP based on interface technology. Share it with everyone for your reference, the details are as follows:

<?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设备的方法
?>
Copy after login

Instance running effect:

The above is the entire content of this article, I hope it will be helpful to everyone's study.


Related recommendations:

php constructor and destructor_php tips

PHPA simple way to generate a txt file to a specified directory_php tips

detailed global error handling of PHP_ php skills

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template