php中trait使用

1 篇文章 0 订阅
<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/10/9 0009
 * Time: 下午 9:44
 */

trait Drive {
    public $carName = 'trait';
    public function driving() {
        echo "driving {$this->carName}<br>";
    }
}
class Person {
    public function eat() {
        echo "eat<br>";
    }
}

//Student 继承了 基类Person 拥有了基类中的eat方法, 通过use  [trait Drive]  可以使用trait 中的 driving方法
// trait解决了单继承的局限性
class Student extends Person {
    use Drive;

    public function study() {
        echo "study<br>";
    }
}
$student = new Student();
$student->study();
$student->eat();
// Notice: Undefined variable: carName
//$student->$carName;
$student->driving();



trait  Say1{
    public function  hi(){
        echo 'say hi from say1<br>';
    }

    public function  hello(){
        echo 'say hello from say1<br>';
    }
}



trait  Say2{

    public function  hi(){
        echo 'say hi from say2<br>';
    }
    public function  hello(){
        echo 'say hello from say2<br>';
    }
}


class ClassSay{
    use Say1,Say2{
        //使用insteadof 来解决不同trait中的同名方法
        Say1::hello insteadof Say2;// say1 中的hello方法 取代  say2的hello方法
        Say2::hi insteadof Say1; // say2的hi方法 取代 say1的 hi方法

        // trait方法取别名
        Say2::hello as heihei; //哪怕上面使用insteadof 这里的heihei别名对应的是trait原有的方法
        Say1::hi as hehe;
    }
}

$csay = new ClassSay;

$csay->hello();
$csay->hi();
$csay->heihei();//say hello from say2
$csay->hehe();//say hi from say1


// trait中可以使用 trait , trait中可以有抽象方法, 静态方法  静态变量


trait T1{
    public  function  hi(){
        echo 't1 hi';
    }
}

trait T2{

    use T1;

    public  abstract function absMethod();
}


class Class3{

    use T2;

    public   function absMethod(){
        echo 'Class3 abs method impl'.'<br>';
    }

    public function  staticMethod(){
        static $i = 0;
        $i++;
        echo 'Class3 staticMethod:'.$i.'<br>';
    }
}


$c3 = new Class3();

$c3->absMethod();

$c3->staticMethod();
$c3->staticMethod();

/*
 * 输出结果:
study
eat
driving trait
say hello from say1
say hi from say2
say hello from say2
say hi from say1
Class3 abs method impl
Class3 staticMethod:1
Class3 staticMethod:2

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值