php之trait 我的笔记

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

相似 class  可是用tarit 写的类 不能被实例化 和继承。如今来看看他的用法ui

<?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() this

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

 

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

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

 仍是直接上代码  耐心看完。。。继承

<?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
相关文章
相关标签/搜索