Blogger Information
Blog 28
fans 0
comment 0
visits 16427
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
trait练习-2018年05月09日01:15
植树青年小江同志的博客
Original
519 people have browsed it

Trait代码复用


实例

<?php

/**
 * Trait是什么?
 * 1.trait是为单继承语言量身定制的代码复用机制;
 * 2.之前可以通过函数或类来实现代码复用;
 * 3.trait可以简单的理解为一个类方法的集合,工作在父类与子类之间;
 * 4.但是trait不仅仅局限于方法集合,还支持抽象,静态与属性;
 * 5.当前类成员会覆盖trait类成员,而trait中的成员,又可以覆盖同名类成员
 * 6.重要提示:trait不是类,不能实例化,切记切记
 */

class Vehicle
{
  protected $name;
  protected $power;

  public function __construct($name,$power='131')
  {
    $this->name = $name;
    $this->power = $power;
  }

  public function accelerate($time='10')
  {
    return $this->name.'拥有'.$this->power.'马力,0-100加速只要'.$time;
  }
}

trait BreakSystem
{
  public $tyre = 'perform';

  public function break($distance='40')
  {
    return $this->name.'刹车距离为'.$distance;
  }

  abstract public static function driver($name);

  public function accelerate($time='8')
  {
    return $this->name.'拥有'.$this->power.'马力,0-100加速只要'.$time;
  }
}

trait Engine
{
  public $technic = 'i-vetc';

  public function race($time='180')
  {
    return $this->name.'的发动机有'.$this->technic.',赛道圈速'.$time.'s';
  }
}

class Civic extends Vehicle
{
  use BreakSystem, Engine;

  public $power = '177';
  

  public static function driver($name)
  {
    return $name;
  }

  public function accelerate($time='7')
  {
    return $this->name.'拥有'.$this->power.'马力,0-100加速只要'.$time;
  }
}

$myCar = new Civic('Civic');

echo Civic::driver('gakkispy');

echo '<hr>';

echo $myCar->accelerate();

echo '<hr>';

echo $myCar->break();

echo '<hr>';

echo $myCar->race();

运行实例 »

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


Correction status:Uncorrected

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!