博客列表 >trait—2018年5月8日11时54分

trait—2018年5月8日11时54分

Gee的博客
Gee的博客原创
2018年05月08日 11:57:03896浏览

实例

<?php

if (!class_exists('Chief')) {
    class Chief
    {
        protected $name;

        public function __construct($name = '厨师长')
        {
            $this->name = $name;
        }

        public function cook($food = '番茄炒蛋')
        {
            return $this->name.'在烧'.$food;
        }
    }
}

if (!trait_exists('Dish')) {
    trait Dish
    {
        public $customer = '顾客';

        public function eat($vegetable = '蔬菜')
        {
            return $this->customer.'在品尝'.$this->name.'烧的'.$vegetable;
        }

        abstract public static function special($name);

        public function cook($food = '蛋黄南瓜')
        {
            return $this->customer.'在试吃'.$food;
        }
    }

    class Apprentice extends Chief
    {
        use Dish;

        protected $name;

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

        public function special($name = '糖醋排骨')
        {
            return $this->name.'特别擅长烧'.$name;
        }

        public function cook($food = '啤酒茄盒')
        {
            return $this->name.'在试吃'.$food;
        }
    }
}

$apprentice = new Apprentice();

echo $apprentice->special().'<br>';
echo $apprentice->cook().'<br>';
echo $apprentice->eat().'<br>';

运行实例 »

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

总结:

  1. trait是为单继承语言量身定制的代码复用机制

  2. trait简单理解为一个方法集合

  3. trait可以看作是一个特殊的类,但不能被实例化,仅允许被类调用

  4. 使用关键字use

  5. 优先级为子类>trait>父类

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