【PHP】面向对象 - 接口(interface)

小破孩
2022-06-19 / 0 评论 / 119 阅读 / 正在检测是否收录...

PHP是单继承语言,因此一个类不能同时继承多个类。当一个类需要多个类的功能时,除了使用trait关键字,还可以使用接口技术。
如果一个抽象类里面的所有方法都是抽象方法,且没有声明变量,而且接口里面所有成员都是public权限的,那么这种特殊的抽象类就是接口。
应用场景:

  • 保持规范、统一性
  • 多个类需要实现同样的方法,只是实现方式不一样

接口使用规范:

  • 接口不能实例化
  • 接口属性必须是常量
  • 接口方法必须是public,且不能有函数体
  • 类必须实现接口的所有方法
  • 一个类可以同时实现多个接口,用逗号隔开
  • 接口可以继承接口,使用extends关键字。
  • 接口使用关键字interface来定义,使用implements关键字来实现
  • 类要实现接口,必须使用和接口中所定义的方法完全一致的方式。否则会导致致命错误.
  • 实现多个接口时,接口中的方法不能有重名。
    <?php
    //定义接口
    interface User{
        function getDiscount();
        function getUserType();
    }
    //VIP用户 接口实现
    class VipUser implements User{
        // VIP 用户折扣系数
        private $discount = 0.8;
        function getDiscount() {
            return $this->discount;
        }
        function getUserType() {
            return "VIP用户";
        }
    }
    class Goods{
        var $price = 100;
        var $vc;
        //定义 User 接口类型参数,这时并不知道是什么用户
        function run(User $vc){
            $this->vc = $vc;
            $discount = $this->vc->getDiscount();
        $usertype = $this->vc->getUserType();
            echo $usertype."商品价格:".$this->price*$discount;
        }
    }
    
    $display = new Goods();
    $display ->run(new VipUser);  //  VIP用户商品价格:80 元 
    ?>
0

评论 (0)

取消