php之trait 个人笔记

自从 php 5.4 起 实现了一种代码复用的方式(tarit)

类似 class 但是用tarit 写的类 不能被实例化 和继承。现在来看看他的用法

<?php
trait A{
    public function Atest()
    {
        echo "this is trait A";
    }
}

class Tese{
    use A;
}
$testObj = new Tese();

echo $testObj->Atest();
//this is trait A

这里直接用use 就可以 相当于 require()

接下来看看 trait 中方法 的优先级 根据官网手册提供是 :

从基类继承的会被 tarit 的方法覆盖 tarit的方法会被 本类(Test)中的 方法覆盖

同时也支持 多个 tarit 用逗号隔开,eg: use A,B,C;

还是直接上代码 耐心看完。。。

<?php
trait A{
    public function Atest(){
        echo "this is trait A".'<br>';
    }
}
class Base{
    public function Atest(){
        echo "this is  baseA".'<br>';
    }
}
class Tese extends Base{
    
    public function Atest(){
        echo "this is class Atest".'<br>';
    }
    use A;
}
$testObj = new Tese();
echo $testObj->Atest();

//this is class Atest