源来页 公告 登陆

 面向对象 PHP 类的接口

composer @Ta
2016-06-02 20:51

例子:
<?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 元 

实现多个接口
PHP也可以在继承一个类的时候同时实现多个接口:
class 子类 extends 父类 implemtns 接口1, 接口2, ...
{
    ......
}

最后编辑:2019-07-28 18:12
阅:2188 发表于2016-06-02 20:51
#php教程
评论:

返回源来页/返回首页


天合之作 曲在人意

心灵鸡汤:
      

®2019-2024 all power by Zlproject3.7
川公网安备 51192202000151号
蜀ICP备2021014921号-2 首页 #top

本网站由提供CDN加速/云储存服务

天合之作 曲在人意