博客列表 >抽象trait实例 -0507

抽象trait实例 -0507

威灵仙的博客
威灵仙的博客原创
2018年05月08日 01:04:43632浏览

实例

实例
<?php
if (!class_exists('Person')) {
  class Person
    {
        protected $name;
        
        public function __construct($name='隔壁老王')
        {
            $this->name = $name;
        }
        
        public function study($hobby='打麻将')
        {
            return $this->name.'在学习'.$hobby;
        }
    
        
    }  
}
if(!trait_exists('Hobby')){ 
    trait Hobby
    {
        public $friend='小华';
        public function sport($name='踢足球')
        {

            return $this->name.'和'.$this->friend.'在'.$name;
        } 
        
       
//        abstract public static function hobby($name);
        
        
       
        public function study($hobby='唱歌')
        {
            return $this->name.'在学习'.$hobby;
        }
    }
}
if(!trait_exists('Recreation')){
    trait Recreation
    {
        //这个trait类中也声明一个与Course中同名的方法sport
        //注意: 属性$friend不允许与Course::sport()同名
        //因为目前trait中还没有处理同名属性的机制,期待新版本会解决
        //这里我们将$friend 修改为 $friend1
        public $friend1='小军';
        public function sport($name='打蓝球')
        {
//            return $this->name.'在学习'.$name;
            //trait中可以访问父类中的属性
            return $this->name.'和'.$this->friend1.'在学习'.$name;
        } 
        
        
    }
}
class Student extends Person
{
    
    use Hobby, Recreation {
      
        Hobby::sport insteadof Recreation;
       
     
        Recreation::sport as mySport;
    }
    
     public static function hobby($name)
    {
        return $name;
    }
      
     public function study($course='斗地主')
    {
        return $this->name.'在学习'.$course;
    }
    
}

//实例化Student类
$student = new Student();

//1.访问父类Person中的方法
echo $student->study();
echo Student::hobby('抽烟喝酒');
echo '<hr>';
echo $student->sport();
echo '<hr>';
echo $student->mySport();


运行实例 »
点击 "运行实例" 按钮查看在线实例


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议