How to use a trait several times in a class?

梦想与她 提交于 2019-12-01 01:02:03

问题


The following code:

trait T {
    function foo() {}
}

class C {
    use T { T::foo as bar; }
    use T { T::foo as baz; }
}

Produces the following error:

Trait method bar has not been applied, because there are collisions with other trait methods on C

Is it possible to use a trait twice in a class?


回答1:


To "import" a method defined in a trait multiple times with different names do this:

class C {
  use T {
    foo as bar;
    foo as baz;
  }
}



回答2:


Yes, you can use a trait twice:

trait T {
    function foo() {}
}

class C {
    use T { T::foo as bar; T::foo as baz; }
}


来源:https://stackoverflow.com/questions/13582061/how-to-use-a-trait-several-times-in-a-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!