trait使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21383977/article/details/85014419

1、php单继承模式,trait突破了单继承,实现了代码复用

<?php
//trait 不能实例化的类
trait Demo1
{
	public function hello1(){
	    return __METHOD__;
	}
}
trait Demo2
{
	public function hello2(){
	    return __METHOD__;
	}
}
class Demo
{
	//使用use实现了代码复用,相当于将Demo1、Demo2中代码剪切到该类中
	use Demo1,Demo2;
	public function hello(){
	    return __METHOD__;
	}
	public function test1(){
	    return $this->hello1();
	}
}
$obj=new Demo;
echo $obj->test1();

2、trait使用中的优先级问题  :当前类中的方法与trait类 ,父类中的方法重名了

a、当前类、trait类、父类都有同名函数  访问当前类

class Demo extends Test
{
	//使用use实现了代码复用,相当于将Demo1、Demo2中代码剪切到该类中
	use Demo1;
	public function hello(){
	    return __METHOD__;
	}
}
$obj=new Demo;
echo $obj->hello();

输出:Demo::hello

b、trait类、父类都有同名函数  访问trait类

class Demo extends Test
{
	//使用use实现了代码复用,相当于将Demo1、Demo2中代码剪切到该类中
	use Demo1;
}
$obj=new Demo;
echo $obj->hello();

输出:Demo1::hello

c、当多个trait类中有同名方法时

class Demo extends Test
{
	//使用use实现了代码复用,相当于将Demo1、Demo2中代码剪切到该类中
	use Demo1,Demo2;
	public function test1(){
	    return $this->hello();
	}
}
$obj=new Demo;
echo $obj->hello();
?>

报错:Fatal error: Trait method hello has not been applied, because there are collisions with other trait methods on Demo in 

定规则访问谁替代谁

class Demo extends Test
{
	//使用use实现了代码复用,相当于将Demo1、Demo2中代码剪切到该类中
	use Demo1,Demo2{
       Demo1::hello insteadof Demo2;
	}
	
	public function test1(){
	    return $this->hello();
	}
}
$obj=new Demo;
echo $obj->hello();
?>

输出:Demo1::hello

多个trait互不影响使用别名:

class Demo extends Test
{
	//使用use实现了代码复用,相当于将Demo1、Demo2中代码剪切到该类中
	use Demo1,Demo2{
       Demo1::hello insteadof Demo2;
       Demo2::hello as Demo2hello;
	}
	
	public function test1(){
	    return $this->hello();
	}
	public function test2(){
	    return $this->Demo2hello();
	}
}
$obj=new Demo;
echo $obj->test2();
?>

猜你喜欢

转载自blog.csdn.net/qq_21383977/article/details/85014419