码迷,mamicode.com
首页 > Web开发 > 详细

php中trait的用法

时间:2018-12-28 10:57:42      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:-o   调用   ffffff   实例   roc   world   图片   image   http   

  • 代码:
    <?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;
    }
    }
  • 测试:
    // 实例化类test的对象objtest
    $objtest = new test();
    // 调用对象objtest的sayhelloworld方法
    $objtest->sayhelloworld();
  • 输出:
    技术分享图片
  • php中trait的用法

    标签:-o   调用   ffffff   实例   roc   world   图片   image   http   

    原文地址:http://blog.51cto.com/12173069/2336229

    (0)
    (0)
       
    举报
    评论 一句话评论(0
    登录后才能评论!
    © 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
    迷上了代码!