zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Jsp 4—— 内置对象
    Jsp 3—— 声明语法
    Jsp 2—— 小脚本
    CF1479B1 Painting the Array I
    P5337 [TJOI2019]甲苯先生的字符串
    CF19C Deletion of Repeats
    CF484D Kindergarten
    CF529B Group Photo 2 (online mirror version)
    CF1068B LCM
    CF554A Kyoya and Photobooks
  • 原文地址:https://www.cnblogs.com/yhl664123701/p/6532515.html
Copyright © 2011-2022 走看看