Blogger Information
Blog 38
fans 0
comment 1
visits 30700
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
5月7日trait实例实现代码复用
1
Original
644 people have browsed it

实例

<meta charset="UTF-8">
<?php
//父类
class Person
{
    //保护属性
    protected $name;
    构造方法
    public function __construct($name)
    {
        $this->name = $name;
    }
    //游戏的方法
    public function play($game)
    {
        return $this->name .'在玩'.$game.'<br>';
    }
}
//trait:简单来说,可以将一些方法存储在trait类里边,需要的时候调用
trait Course
{
    public $friend = '小红';
    //方法
    public function sleep($time)
    {
        return $this->name.$time.'睡觉'.'<br>'.$this->friend.$time.'睡觉'.'<br>';
    }
    //抽象类
    abstract public function hobby ($name);
    //方法
    public function study($course = 'java')
    {
        return $this->friend.'在学习'.$course;
    }

}
//子类
class Member extends Person
{
    //使用trait Course类
    use Course;
    //hobby方法
    public function hobby($name)
    {
       return $name;
    }

    public function study($course = 'python')
    {
        return $this->friend.'在学习'.$course;
    }

}
//实例化子类
$member = new Member('父类');

echo $member->play('游戏');
echo $member->sleep('9点');
echo $member->study();

运行实例 »

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


Correction status:Uncorrected

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
  • 1
    2018-03-16 00:39:40