Blogger Information
Blog 36
fans 0
comment 1
visits 28167
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
trait实例
其琛的博客
Original
870 people have browsed it

代码如下

<?php
    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='打篮球')
        {
            $this->name.'和'.$this->friend.'在'.$name;
    }

        public function hobby($name)
        {
            return $this->name.'爱好'.$name;
        }
        public function study($course = '英语')
        {
            return $this->name.'学习'.$course.'学不会';
        }
    }
}
class Student extends Person
{
    use Course;
}

    class Worker
    {
        use Course;

        private $name;

        public function __construct($name)
        {
            $this->name = $name;
        }

        public function __get($name)
        {
            return $this->$name;
        }
    }
$student = new Student();
echo $student->study().'<br>';
echo $student->hobby('打篮球').'<br>';
$worker = new Worker('小五');
echo $worker->name.'<br>';
echo $worker->hobby('打游戏');
  • 运行结果9VOB0MN]6K[JY~BIOSSQGG8.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