php – 与其他特征方法的冲突

如何用同名方法处理特征?
trait FooTrait {
  public function fooMethod() {
        return 'foo method';
  }

  public function getRow() {
        return 'foo row';
  }
}

trait TooTrait {
    public function tooMethod() {
        return 'too method';
    }

    public function getRow() {
        return 'too row';
    }
}

class Boo
{
    use FooTrait;
    use TooTrait;

    public function booMethod() {
        return $this->fooMethod();
    }
}

错误,

Fatal error: Trait method getRow has not been applied,because there
are collisions with other trait methods on Boo in…

我该怎么办?

而且,使用两个相同的方法名称,如何从trait FooTrait获取方法

$a = new Boo;
var_dump($a->getRow()); // Fatal error: Call to undefined method Boo::getRow() in...

编辑:

class Boo
{
    use FooTrait,TooTrait {
        FooTrait::getRow insteadof TooTrait;
    }

    public function booMethod() {
        return $this->fooMethod();
    }
}

如果我想通过Boo从TooTrait获取getRow的方法呢?可能吗?

PHP关于冲突的文档:

If two Traits insert a method with the same name,a fatal error is
produced,if the conflict is not explicitly resolved.

To resolve naming conflicts between Traits used in the same class,the
insteadof operator needs to be used to chose exactly one of the
conflicting methods.

Since this only allows one to exclude methods,the as operator can be
used to allow the inclusion of one of the conflicting methods under
another name.

Example #5 Conflict Resolution

In this example,Talker uses the traits A and B. Since A and B have
conflicting methods,it defines to use the variant of smallTalk from
trait B,and the variant of bigTalk from trait A.

The Aliased_Talker makes use of the as operator to be able to use B’s
bigTalk implementation under an additional alias talk.

<?PHP trait A {
     public function smallTalk() {
         echo 'a';
     }
     public function bigTalk() {
         echo 'A';
     } }

 trait B {
     public function smallTalk() {
         echo 'b';
     }
     public function bigTalk() {
         echo 'B';
     } }

 class Talker {
     use A,B {
         B::smallTalk insteadof A;
         A::bigTalk insteadof B;
     } }

 class Aliased_Talker {
     use A,B {
         B::smallTalk insteadof A;
         A::bigTalk insteadof B;
         B::bigTalk as talk;
     } }

所以在你的情况下可能是

class Boo
{
    use FooTrait,TooTrait {
        FooTrait::getRow insteadof TooTrait;
    }

    public function booMethod() {
        return $this->fooMethod();
    }
}

(即使你单独使用也可以工作,但我认为更清楚)

或者使用as来声明一个别名.

相关文章

Hessian开源的远程通讯,采用二进制 RPC的协议,基于 HTTP 传输。可以实现PHP调用Java,Python,C#等多语...
初识Mongodb的一些总结,在Mac Os X下真实搭建mongodb环境,以及分享个Mongodb管理工具,学习期间一些总结...
边看边操作,这样才能记得牢,实践是检验真理的唯一标准.光看不练假把式,光练不看傻把式,边看边练真把式....
在php中,结果输出一共有两种方式:echo和print,下面将对两种方式做一个比较。 echo与print的区别: (...
在安装好wampServer后,一直没有使用phpMyAdmin,今天用了一下,phpMyAdmin显示错误:The mbstring exte...
变量是用于存储数据的容器,与代数相似,可以给变量赋予某个确定的值(例如:$x=3)或者是赋予其它的变...