<?php
/**
* trait实现了代码复用
* 并且突破了单继承的限制
* trait是类不是类,不能实例化
*
* trait优先级的问题
* 1.当前类中的方法与trait类,父类中的方法重名了,怎么办?
* trait类的优先级是高于同名父类方法
*
* 2.当多个trait类中有同名的方法,怎么办?
*设置一条规则
* use Demo,Demo2
* {
Demo1 ::hello insteadof Demo2; 当访问hello方法时 Demo1替代掉Demo2中hello方法
* Demo2 ::hello as Demo2hello;给Demo2中的方法起一个别名 这样hello方法就不会失效
* }
*
*/
trait Demo1
{
public function hello1()
{
return __METHOD__;
}
}
trait Demo2
{
public function hello2()
{
return __METHOD__;
}
}
class Demo
{
use Demo1,Demo2;
public function hello()
{
return __METHOD__;
}
public function test1()
{
return $this->hello1();
}
public function test2()
{
return $this->hello2();
}
}
$obj = new Dome();
echo $obj->hello();//访问Demo中的hello方法
echo $obj->test1();//访问Demo1中的hello1方法
echo $obj->test2();//访问Demo2中的hello2方法
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号