Blogger Information
Blog 64
fans 2
comment 3
visits 75566
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
trait,代码复用—2018年5月8日09:09:02
清雨的博客
Original
591 people have browsed it

实例

<?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

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