Blogger Information
Blog 31
fans 0
comment 2
visits 27487
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
5月7日作业—— 写一个trait实例,实现代码复用
钱光照的博客
Original
717 people have browsed it

写一个trait实例,实现代码复用:

1.源码如下:

实例

<?php

/**
 * 学生类申明
 */
if (!class_exists('Student'))
{
    class Student
    {
        protected $id;//学号
        protected $name;//姓名
        
        public function __construct($name='张三')
        {
            $this->name=$name;
        }
        
        public function study($course='语文') 
        {
            return $this->name.'在学习'.$course;        
        }    
    }
}

if(!trait_exists('Course')){
    trait Course
    {
        public $num=13;//课程数
        public function study($course='数学')
        {
            return $this->name.'在学习'.$course;
        }
    }    
}

if(!trait_exists('Sport')){
    trait Sport
    {
        public $sport='踢足球';
        public function sport($sport='打篮球')
        {
            return $this->name.'会'.$sport;
        }
    }    
}

class Member extends Student
{
    use Course,Sport{}
    public function study($course = '英语')
    {
        parent::study($course);
        return $this->name.'在学习'.$course;
    }
}

$member = new Member();
//1.访问父类Person中的方法
echo $member->study();

echo '<hr>';
//
////2.访问trait类中的方法
echo $member->sport();
//
echo '<hr>';
//
//
//3.当trait中存在与父类同名方法时,trait优先级要高,当子类中存在与trait类同名方法时,子类优先级要高
echo $member->study();
//4.子类可以从多个trait中获取方法集
//
echo '<hr>';
echo $member->sport();

运行实例 »

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


2.运行结果:

1.png

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