Trait的使用
Trait是为类似PHP的单继承语言而准备的一种代码复用机制.
Trait为了减少单继承语言的限制,使开发人员能够自由的在不同层次结构内独立的类中复用method
index.php
<?php
spl_autoload_register(function($className){
$file='./'.$className.'.php';
if(!file_exists($file)){
throw new Exception("Class not found!");
}
require_once $file;
});
$car=new Car();
$car->test();
$car->Gps();
echo '<br/>';
$mobile=new Mobile();
$mobile->test();
$mobile->Gps();
?>
Gps.php
<?php
Trait Gps
{
public function gps(){
echo 'gps';
}
}
?>
Mobile.php
<?php
class Mobile
{
use Gps;
public function test(){
echo 'Mobile';
}
}
?>
Car.php
<?php
class Car
{
use Gps;
public function test()
{
echo 'Car';
}
}
?>
引用多个Trait的时候如果不同的Trait中方法同名,会发生冲突: Trait method Gps has not been applied, because there are collisions with other trait methods on Car in E:\wamp\www\Test\Car.php on line 13.
解决冲突的方法需要使用:insteadof
<?php class Car { use Gps,GpsChina{ GpsChina::Gps insteadof Gps; //代表使用GpsChina下的Gps方法,而不是使用原来的Gps方法 } public function test() { echo 'Car'; } } ?>
优先级为:继承类的方法<Trait的方法<类中的方法
浙公网安备 33010602011771号