trait使用

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();
?>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值