Blogger Information
Blog 44
fans 3
comment 3
visits 33821
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
trait实例--5月7日作业
唔良人
Original
839 people have browsed it

实例

<?php
//申明一个父类:Person
class Person
{
    public $name;
    //初始化$name
    public function __construct($name = '小明')
    {
        $this->name = $name;
    }

    //申明一个run()方法
    public function run()
    {
        return $this->name . '在跑';
    }
}

//申明trait
trait myTrait
{
    public $friend = '小花';
    public function eat()
    {
        return $this->name . '吃东西';
    }

    public function run()
    {
        return $this->name."和".$this->friend.'在跑';
    }
    public function study($course = 'java')
    {
        return $this->name . '在学习' . $course;
    }
}

class Student extends Person
{
    //使用trait
    use myTrait;

    //重写study()方法
    public function study($course='python')
    {
        return $this->name.'在学习'.$course;
    }
}

$study = new Student();
echo $study->run().'<br>';
echo $study->eat().'<br>';
echo $study->study().'<br>';

运行实例 »

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



最终效果:

QQ截图20180509162551.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