Blogger Information
Blog 24
fans 0
comment 0
visits 18491
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
接口使用场景、trait基本功能
昔年
Original
760 people have browsed it
  1. 接口使用场景

     单接口

    接口可以突破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.'<br>';
    }
    

    public function fly()
    {
        return '我可以飞行';
    }
}

$bird = new Bird;

echo $bird->eatFood();
echo $bird->fly();

demo.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.'<br>';
    }
}

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();

demo2.png

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

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:trait的作用, 许多人还没有意识到, 相信以后它的使用场景会越来越多
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!