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?
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.
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.
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.
Definition of Class Trait (noun) A behavior, custom, or norm–either real or imagined–that define or reflect a class.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With