查看: 119|回复: 0

[tp6] php使用interface可以implements多个接口实现

[复制链接]

748

主题

39

回帖

3907

积分

管理员

总舵主

积分
3907
QQ
发表于 2026-5-29 15:11:48 | 显示全部楼层 |阅读模式
在interface中约束方法,则在implements的类中必须要实现接口中约束的方法,示例如下:

1、在app\intfaceclass目录创建CanFly.php类,代码如下:
  1. <?php

  2. namespace app\intfaceclass;

  3. interface CanFly
  4. {
  5.     // 接口可以定义常量
  6.     const API_URL = 'http://tp.com';
  7.     // 接口不能有属性
  8.    
  9.     // 接口类中只写方法,不具体写函数体
  10.     public function fly();
  11. }
复制代码

2、在app\controller目录创建Plan.php和AirPlan.php两个控制器类,代码如下:
  1. <?php

  2. namespace app\controller;

  3. use app\intfaceclass\CanFly;

  4. class Plane implements CanFly
  5. {
  6.     /**
  7.      * 首页
  8.      */
  9.     public function index()
  10.     {
  11.         return '这是飞机首页';
  12.     }
  13.    
  14.     /**
  15.      * 必须实现接口中定义的fly方法
  16.      */
  17.     public function fly()
  18.     {
  19.         return '飞机飞起来了';
  20.     }
  21. }
复制代码
  1. <?php

  2. namespace app\controller;

  3. use app\intfaceclass\CanFly;

  4. class AirPlane implements CanFly
  5. {
  6.     /**
  7.      * 飞行器首页
  8.      */
  9.     public function index()
  10.     {
  11.         return '这里是飞行器首页';
  12.     }
  13.    
  14.     /**
  15.      * 必须实现接口定义的fly方法
  16.      */
  17.     public function fly()
  18.     {
  19.         return '飞行器飞起来了';
  20.     }
  21. }
复制代码
如果在Plane.php和AirPlane.php中不实现fly()方法,则会报错。
道不同,不相为谋!理想要有,万一实现了呢?
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注公众号

相关侵权、举报、投诉及建议等,请发 E-mail:2513533699@qq.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.|鲁ICP备19000917号|鲁公网安备37078302000320号

在本版发帖
关注公众号
QQ客服返回顶部