博客列表 >trait,代码复用—2018年5月8日09:09:02

trait,代码复用—2018年5月8日09:09:02

清雨的博客
清雨的博客原创
2018年05月08日 09:10:04584浏览

实例

<?php
//声明父类: Person
if (!class_exists('Person')) {
    class Person
    {
        protected $name;
        public function __construct($name='郭德纲')
        {
            $this->name = $name;
        }
        public function study($course='喝红酒')
        {
            return $this->name.'的爱好'.$course;
        }
    }
}
if(!trait_exists('Course')){
    trait Course
    {
        public $friend='于谦';
        public function sport($name='吹牛皮')
        {
            return $this->name.'和'.$this->friend.'的爱好'.$name;
        }
        abstract public static function hobby($name);
        public function study($course='装孙子')
        {
            return $this->name.'的爱好'.$course;
        }
    }
}
if(!trait_exists('Recreation')){
    trait Recreation
    {

        public $friend1='郭麒麟';
        public function sport($name='赌博')
        {
            return $this->name.'和'.$this->friend1.'的爱好'.$name;
        }
    }
}
class Student extends Person
{
    use Course, Recreation {
        Course::sport insteadof Recreation;
        Recreation::sport as mySport;
    }
    public static function hobby($name)
    {
        return $name;
    }

    public function study($course='python')
    {
        return $this->name.'的爱好'.$course;
    }
}
//实例化Student类
$student = new Student();
echo '<hr>';
//1.访问父类Person中的方法
//echo $student->study();
echo Student::hobby('抽烟喝酒烫头');
echo '<hr>';
echo $student->sport();
echo '<hr>';
echo $student->mySport();

运行实例 »

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

e.png

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