PHP中trait的使用实现多继承,有同名方法,优先级 子类>trait>父类
实例
<?php /** * */ class Mobile { private $name; public function __construct($name) { $this->name=$name; } public function call($num='180') { return $this->name.'call:'.$num; } } trait Xiaomi { private $name='Xiaomi'; public function call($num='189'){ return $this->name.' call:'.$num; } } class Apple extends Mobile { use Xiaomi; public function __construct($name) { parent::__construct($name); } // public function call($num = '188') // { // return $this->name.' call:'.$num; // } } $apple=new Apple('apple'); echo $apple->call();
运行实例 »
点击 "运行实例" 按钮查看在线实例
输出trait的方法 Xiaomi call:188