如何使用不同命名空间中的特征和 类 消除特征方法冲突?

How can i remove trait method collisions using traits and classes that are in different namespaces?

我不断收到 php 错误,表明该方法不在当前 class 中或存在冲突。查看错误:

Trait method callMe has not been applied, because there are collisions with other trait methods on Src\Classes\A in
C:\wamp\www\src\classes\a.php on line 72

我试过了,但找不到解决办法。这就是我想要实现的目标:

trait A // namespace Src\Traits;
{
     function callMe()
     {}
}
trait B // namespace Src\PowerTraits;
{
     function callMe()
     {}
}
class A // Namespace Src\Classes;
{
    use \Src\Traits\A;
    use \Src\PowerTraits\B {
        A::callMe insteadof B::callMe;
    }
}

当我尝试时

A::callMe insteadof callMe;

出现如下错误(明白了,明显是命名空间错误):

Could not find trait Src\Classes\callMe

也尝试过:

\Src\Traits\A::callMe insteadof \Src\Traits\B::callMe (error, syntax error);
\Src\Traits\A::callMe insteadof B::callMe (error: wrong namespace);
\Src\Traits\A::callMe as NewA (error, collision warning);
\Src\Traits\A::callMe as \Src\Traits\A::NewA (error, syntax error);

不理会,给出碰撞警告:

Trait method callMe has not been applied, because there are collisions with other trait methods

当特征和调用 class 都在不同的命名空间中时,如何覆盖特征方法?

关于 A::callMe insteadof B::callMe

  • 当使用 insteadof 时,您不能在范围解析运算符 :: (Paamayim Nekudotayim) 之后命名方法,因为 PHP 将查找同名的方法。 A::callMe insteadof B;
  • 您需要 use/import/alias class 名称,或引用具有命名空间 \Src\Traits\A::callMe insteadof \Src\PowerTraits\B;
  • 的完全限定 class

演示:https://3v4l.org/g1ltH

<?php

namespace Src\Traits
{
    trait A
    {
        function callMe()
        {
            echo 'Trait A';
        }
    }
}

namespace Src\PowerTraits
{
    trait B
    {
        function callMe()
        {
            echo 'PowerTrait B';
        }
    }
}

namespace Src\Classes
{
    class A
    {
        use \Src\Traits\A;
        use \Src\PowerTraits\B {
            \Src\Traits\A::callMe insteadof \Src\PowerTraits\B;
        }
    }
}

namespace
{
    (new \Src\Classes\A)->callMe();
}

Trait A