Blogger Information
Blog 51
fans 3
comment 1
visits 36233
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
trait—2018年5月8日11时54分
Gee的博客
Original
910 people have browsed it

实例

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

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