php 接口使用场景,接口使用场景、trait基本功能

接口使用场景

单接口

接口可以突破PHP类的继承限制,允许多继承,形成了多层级的接口

用抽象类来部分实现一个接口

接口是实现多态的重要手段<?php

interface Animal

{

const MOTION = 'fly';

public function eatFood();

}

abstract class Flying

{

abstract public function fly();

}

class Bird extends Flying implements Animal

{

public function eatFood()

{

return __CLASS__.'吃虫子'.',拥有技能:'.Bird::MOTION.'
';

}

public function fly()

{

return '我可以飞行';

}

}

$bird = new Bird;

echo $bird->eatFood();

echo $bird->fly();

d6a7a15328740381b04dabcd62f48023.png

2trait:与抽象类,接口一样不能实例化,只能嵌入到宿主类中使用<?php

trait tUniversity

{

protected $area;

protected $totalPeroson;

public function setIntroduce($area,$totalPeroson){

$this->area = $area;

$this->totalPeroson = $totalPeroson;

}

public function getIntroduce(){

echo '占地面积:'.$this -> area.'校园总人数:'.$this -> totalPeroson.'
';

}

}

class Peking

{

use tUniversity;

}

$peking = new Peking();

$area = '约7000亩';

$totalPeroson = '三万五千多';

$peking->setIntroduce($area,$totalPeroson);

$peking->getIntroduce();

class Tsinghua

{

use tUniversity;

}

$tsingHua = new Tsinghua;

$area = '392.4公顷';

$totalPeroson = '四万七千多';

$tsingHua->setIntroduce($area,$totalPeroson);

$tsingHua->getIntroduce();

14205c3e570c84d6ee2401ded3b287d0.png

总结:接口中只允许有抽象方法以及常量,接口中的方法默认就是抽象的,它的抽象类的一种升级,抽象类中还可以有其他属性;trait很好的实现了代码的复用,trait中可以有常规属性、静态属性以及抽象属性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值