php中trait的用法

  1. 代码:
    <?php
    /*
    * 定义trait:test1
    */
    trait test1{
    public function sayhello(){
        echo 'hello';
    }
    }
    /*
    * 定义trait:test2
    */
    trait test2{
    public function sayworld(){
        echo 'world';
    }
    }
    /*
    * 定义类test,继承自trait:test1,test2
    */
    class test{
    use test1,test2;
    /*
     * 定义类test的方法:sayhelloworld
     */
    public function sayhelloworld(){
        // 使用trait:test1中的sayhello方法
        $hello = $this->sayhello();
        // 使用trait:test2中的sayworld方法
        $world = $this->sayworld();
        echo $hello.$world;
    }
    }
  2. 测试:
    // 实例化类test的对象objtest
    $objtest = new test();
    // 调用对象objtest的sayhelloworld方法
    $objtest->sayhelloworld();
  3. 输出:
    php中trait的用法

    广告

    给大家推荐几个好用的工具

  4. 时间校验工具
  5. ip查询工具
  6. 二维码生成工具
  7. json格式化工具
  8. 时间缀-时间转换工具