如何在不冲突的情况下在另一个特征中使用 PHP 特征?
How to use a PHP trait in another trait without conflict?
所以基本上这是代码:在我的 trait Greeting 中,我想使用另一个非常有用的 trait Word。但是现在如果class使用了Greeting,它就不能再使用Word了,虽然我用了别名。
当然我可以使用 insteadof
但对于使用我的库的人来说,错误来自何处以及涉及哪些特征并不明显。为什么这里有冲突,是否有语法技巧可以避免使用 instead 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
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");
所以经过一个小的研究,我发现特征函数的 as
运算符创建了一个别名,但没有重命名该函数。所以 Greeting
特征仍然在使用它的 class 中创建一个 hello
函数。
相关问题:Why method renaming does not work in PHP traits?
(作为个人笔记,我认为这是非常糟糕的设计)。
(Parent)特征的可能解决方案使用另一个特征,而 class 同时使用:
Parent特质:
use App\MyTrait as _MyTrait;
trait ParentTrait
{
use _MyTrait {
_MyTrait::someFunction as _someFunction;
}
}
所以基本上这是代码:在我的 trait Greeting 中,我想使用另一个非常有用的 trait Word。但是现在如果class使用了Greeting,它就不能再使用Word了,虽然我用了别名。
当然我可以使用 insteadof
但对于使用我的库的人来说,错误来自何处以及涉及哪些特征并不明显。为什么这里有冲突,是否有语法技巧可以避免使用 instead 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
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");
所以经过一个小的研究,我发现特征函数的 as
运算符创建了一个别名,但没有重命名该函数。所以 Greeting
特征仍然在使用它的 class 中创建一个 hello
函数。
相关问题:Why method renaming does not work in PHP traits?
(作为个人笔记,我认为这是非常糟糕的设计)。
(Parent)特征的可能解决方案使用另一个特征,而 class 同时使用:
Parent特质:
use App\MyTrait as _MyTrait;
trait ParentTrait
{
use _MyTrait {
_MyTrait::someFunction as _someFunction;
}
}