美文网首页
php接口类interface

php接口类interface

作者: 尤涅 | 来源:发表于2017-04-15 12:32 被阅读0次

在学习框架阅读框架源码的时候,会看到底层很多interface类,类中定义了一些方法,但仅仅就是定义了方法而已,称作接口对象。对于php的interface类,实现接口用implements,并且必须完全实现接口类中的方法,例如:

//定义接口

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元。

user接口类,之提供了用户折扣方法,VipUser类实现了具体折扣系数,goods类实现了不同用户的折扣系数。

所以对于一个团队开发的项目,比如我 负责Vip用户的折扣,你负责其他用户的折扣,我们只要定义好一个interface,在我们逻辑 中去实现这个类就可。

php也能在继承一个类的时候实现多接口:

class A extends B implements C,D{}

相关文章

  • php接口类interface

    在学习框架阅读框架源码的时候,会看到底层很多interface类,类中定义了一些方法,但仅仅就是定义了方法而已,称...

  • 接口

    interface 接口 implements 类实现接口 public interface 接口名{ 接口的成员...

  • PHP OOP小结

    PHP面向对象 继承 设计一个MySQL数据库操作类 抽象类,抽象方法 接口 interface 类的自动加载

  • 第三章②接口

    接口(interface)是与类并行的一个概念 接口声明格式:interface接口名 类声明格式:class类名...

  • PHP接口interface

    1、接口的基本概念? 1)PHP 类是单继承,也就是不支持多继承。2)当一个类需要多个类的功能时,单继承就无能为力...

  • 2020-07-23(接口)

    1,接口特点 * a:接口用关键字interface表示, interface 接口名 {} * b:类实现接口用...

  • 接口

    接口关键字:interface, 实现implement 事物的扩展功能使用接口interface 类名{} 在类...

  • 2020-06-21接口

    接口 接口的特点 接口用关键字interface修饰:public interface 接口名{} 类实现接口用i...

  • Java 接口(interface)

    接口用关键字interface表示格式:interface 接口名 {} 类实现接口用implements表示格式...

  • java中的接口

    接口的特点: A:接口用关键字interface表示;格式:interface 接口名{}B:类实现接口用imp...

网友评论

      本文标题:php接口类interface

      本文链接:https://www.haomeiwen.com/subject/blynattx.html