Why we are not allowed to extend Traits with Classes in PHP?
For example:
Trait T { }
Class C use T {}
/* or */
Class C extends T {}
Is there any potential conflict for such syntax? I do not think so.
The PHP manual states thus:
Traits is a mechanism for code reuse in single inheritance languages such as PHP. 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. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.
If you're looking to extend a trait, then it should probably be a class. If you have a set of methods in one class that you want to use in others, but it feels inappropriate to extend the class (eg. class Animal extends Vehicle
), then in PHP 5.4 it could work well as a trait.
To answer the question more directly, you don't 'extend' a trait, but you can create traits which themselves use other traits. As per the PHP manual:
trait Hello {
public function sayHello() {
echo 'Hello ';
}
}
trait World {
public function sayWorld() {
echo 'World!';
}
}
trait HelloWorld {
use Hello, World;
}
class MyHelloWorld {
use HelloWorld;
}
You can consider this to be a way to maintain your traits in logical groups, and to introduce some modularity.
Edit: having seen some of the comments, I think it's worthwhile to note that using a trait in a base class also means that trait is in any class that extends it, and the trait's functions take precedence over the base class'. Putting it in the child class would merely make the trait's functions unavailable to the parent/base class.
Parent > Trait > Child