How to use a trait several times in a class?

2019-02-17 02:28发布

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?

标签: php traits
2条回答
forever°为你锁心
2楼-- · 2019-02-17 03:04

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;
  }
}
查看更多
Ridiculous、
3楼-- · 2019-02-17 03:06

Yes, you can use a trait twice:

trait T {
    function foo() {}
}

class C {
    use T { T::foo as bar; T::foo as baz; }
}
查看更多
登录 后发表回答