Blogger Information
Blog 60
fans 0
comment 1
visits 37557
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
抽象trait实例 -0507
威灵仙的博客
Original
641 people have browsed it

实例

实例
<?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();


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


Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post