所以基本上这是代码:在我的特征问候中,我想使用另一个非常有用的特征Word。但是,现在如果一个类使用Greeting,尽管我使用了别名,但它不再可以使用Word。
我当然可以使用insteadof
,但是对于使用我的库的人来说,错误来自何处以及涉及哪些特征并不明显。为什么这里有冲突,并且有语法上的技巧来避免使用of而不是?谢谢。
trait Word {
public function hello()
{
return 'hello';
}
}
trait Greeting {
use Word {
Word::hello as _word_hello;
}
public function greet($name)
{
return $this->_word_hello() . " $name";
}
}
class Test {
use Word;
use Greeting;
}
PHP Fatal error: Trait method hello has not been applied, because there are collisions with other trait methods on Test in traits.php on line 20
答案 0 :(得分:2)
因此,经过一番研究,我发现traits函数的as
运算符创建了一个别名,但没有重命名该函数。因此,Greeting
特征仍然在使用它的类中创建一个hello
函数。
相关问题:Why method renaming does not work in PHP traits?
(作为个人笔记,我认为这是非常糟糕的设计)。
答案 1 :(得分:0)
使用另一个特质来解决(父)特质的可能解决方案,而一个类同时使用这两个特质:
ParentTrait:
use App\MyTrait as _MyTrait;
trait ParentTrait
{
use _MyTrait {
_MyTrait::someFunction as _someFunction;
}
}
答案 2 :(得分:-1)
Word
在Greeting
中已经存在,因此无需在Test
中再次定义它,因此,您会得到该错误:
trait Word {
public function hello()
{
return 'hello';
}
}
trait Greeting {
use Word {
Word::hello as _word_hello;
}
public function greet($name)
{
return $this->_word_hello() . " $name";
}
}
class Test {
#use Word;
use Greeting;
}
$test = new Test();
echo $test->greet("Ahmad");