博客列表 >trait实例

trait实例

其琛的博客
其琛的博客原创
2018年05月10日 14:47:13862浏览

代码如下

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

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