Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a trait several times in a class?

Tags:

php

traits

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?

like image 345
BenMorel Avatar asked Nov 27 '12 10:11

BenMorel


People also ask

Can a trait use another trait?

A trait is similar to a class but for grouping methods in a fine-grained and consistent way. It is not allowed to instantiate a trait on its own. So a trait is just a container for a group of methods that you can reuse in another classes.

Can you extend a trait?

Unlike a class, what's important to remember, is that you cannot add extends or implements to a trait. You can't instantiate a trait, either. Their sole purpose is to support our classes, and not to replace them. Traits can have methods, just like classes do.

What is the use of traits?

A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

What is a trait class?

Definition of Class Trait (noun) A behavior, custom, or norm–either real or imagined–that define or reflect a class.


1 Answers

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;
  }
}
like image 184
Matteo Tassinari Avatar answered Oct 06 '22 07:10

Matteo Tassinari