<?php
/*
* trait 优先级的问题
* 1. 当前类中的方法与trati类中的方法重名怎么办?
* 2. 以下实例演示:
当前类Demo中存在方法hello()方法
当前类继承的Test类中也存在hello()方法
trait Demo1()类中也存在 hello()方法
那么?优先级如何判断呢?
* 3. 优先级:当前类Demo中的hello()方法 高于 trait Demo1类中的hello()方法 高于 当前类Demo父类Test类中的hello()方法
*/
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{
// 在Demo类中继承Demo1、demo2类,使用use
use Demo1,Demo2;
public function hello(){
return __METHOD__;
}
public function test1(){
// 在test1方法中访问Demo1中的hello1方法
return $this->hello1();
}
public function test2(){
// 在test2方法中访问Demo2中的hello2方法
return $this->hello2();
}
}
$obj = new Demo;
echo $obj->hello(); // 输出Demo中的hello();
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号