代码:
- <?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();
输出:
来源: http://www.bubuko.com/infodetail-2900089.html