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

PHP Trait特性

时间:2018-10-19 14:19:16      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:use   name   特性   new   echo   组合   strong   http   inf   

php类的单继承性,无法同时从两个基类中继承属性和方法,为了解决这个问题,使用Trait特性解决.
用法:通过在类中使用use 关键字,声明要组合的Trait名称,具体的Trait的声明使用Trait关键词.  注意:Trait不能实例化

 

demo示例:

 1 <?php
 2 trait Dog{
 3     public function dog(){
 4     echo ‘This trair dog‘;
 5     }
 6 }
 7 
 8 trait Fish{
 9     public function fish(){
10     echo ‘This trair fish‘;
11     }
12 }
13 
14 
15 class Animal{
16     public function name(){
17         echo ‘This is animal‘;
18     }
19 }
20 
21 class Cat extends Animal{
22     use Dog,Fish;
23     public function eat(){
24         echo ‘This is animal cat eat‘;
25     }
26 }
27 
28 $data = new Cat();
29 $data->name();//This is animal
30 echo ‘<pre>‘;
31 $data->eat();//This is animal cat eat
32 echo ‘<pre>‘;
33 $data->dog();//This trair dog
34 echo ‘<pre>‘;
35 $data->fish();//This trair fish

 

结果打印:

技术分享图片

PHP Trait特性

标签:use   name   特性   new   echo   组合   strong   http   inf   

原文地址:https://www.cnblogs.com/cxx8181602/p/9815669.html

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