trait突破了单继承的限制
trait类的优先级是高于同名父类方法 子类 >trait >父类
多个trait类中有同名的方法,Demo1::hello insteadof Demo2;代替Demo2
3.1想输出trait的Demo2中hello()方法 给hello改个名 Bhello;
1.trait突破了单继承的限制示例:
<?php
/**
* trait实现了代码的复用
* trait是类不是类,不能实例化
* 1.trait突破了单继承的限制示例
*/
trait Demo1
{
public function hello1(){
return __METHOD__;
}
}
trait Demo2
{
public function hello2(){
return __METHOD__;
}
}
class Demo
{
// 注:use在这里不是导入命名空间,而是引入Demo1,Demo2这两个类到Demo类,这样可以突破了单继承
use Demo1,Demo2;
public function hello(){
return __METHOD__;
}
public function test1(){
return $this->hello1();
}
public function test2(){
return $this->hello2();
}
}
$obj = new Demo;
echo $obj->hello();
echo '<hr>';
echo $obj->test1();
echo '<hr>';
echo $obj->test2();
<?php
/**
* 2.trait类的优先级是高于同名父类方法 子类 >trait >父类
*/
trait Demo1
{
public function hello(){
return __METHOD__;
}
}
trait Demo2
{
public function hello2(){
return __METHOD__;
}
}
class Test
{
public function hello(){
return __METHOD__;
}
}
class Demo extends Test
{
use Demo1,Demo2;
// public function hello(){
// return __METHOD__;
// }
public function test1(){
return $this->hello1();
}
public function test2(){
return $this->hello2();
}
}
$obj = new Demo;
echo $obj->hello();<?php
/**
*3.trait优先级问题:当多个trait类中有同名的方法,怎么办?
* 多个trait类中有同名的方法,Demo1::hello insteadof Demo2;代替Demo2
*3.1想输出trait的Demo2中hello()方法 给hello改个名 Bhello;
*/
trait Demo1
{
public function hello(){
return __METHOD__;
}
}
trait Demo2
{
public function hello(){
return __METHOD__;
}
}
class Test
{
public function hello(){
return __METHOD__;
}
}
class Demo extends Test
{
use Demo1,Demo2{
//多个trait类中有同名的方法,Demo1::hello insteadof Demo2;代替Demo2
//想输出trait的Demo2中hello()方法 给hello改个名 Bhello;
Demo1::hello insteadof Demo2;
Demo2::hello as Bhello;
}
// public function hello(){
// //返回一个类的静态方法
// return __METHOD__;
// }
public function test1(){
//返回一个类的静态方法
return $this->hello();
}
public function test2(){
//返回一个类的静态方法
return $this->Bhello();
}
}
$obj = new Demo;
echo $obj->hello();
echo '<hr>';
echo $obj->test1();
echo '<hr>';
echo $obj->test2();
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号