admin 发表于 2026-5-29 15:11:48

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

在interface中约束方法,则在implements的类中必须要实现接口中约束的方法,示例如下:

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

namespace app\intfaceclass;

interface CanFly
{
    // 接口可以定义常量
    const API_URL = 'http://tp.com';
    // 接口不能有属性
   
    // 接口类中只写方法,不具体写函数体
    public function fly();
}
2、在app\controller目录创建Plan.php和AirPlan.php两个控制器类,代码如下:
<?php

namespace app\controller;

use app\intfaceclass\CanFly;

class Plane implements CanFly
{
    /**
   * 首页
   */
    public function index()
    {
      return '这是飞机首页';
    }
   
    /**
   * 必须实现接口中定义的fly方法
   */
    public function fly()
    {
      return '飞机飞起来了';
    }
}
<?php

namespace app\controller;

use app\intfaceclass\CanFly;

class AirPlane implements CanFly
{
    /**
   * 飞行器首页
   */
    public function index()
    {
      return '这里是飞行器首页';
    }
   
    /**
   * 必须实现接口定义的fly方法
   */
    public function fly()
    {
      return '飞行器飞起来了';
    }
}如果在Plane.php和AirPlane.php中不实现fly()方法,则会报错。
页: [1]
查看完整版本: php使用interface可以implements多个接口实现