In PHP 5.4.9, the following example triggers the fatal error "B has colliding constructor definitions coming from traits".
trait T {
public function __construct () {
echo __CLASS__ . ": constructor called.\n";
}
}
class A {
use T;
}
class B extends A {
use T;
}
There's no problem when the trait contains a different method than the constructor, and no problem when the constructor is actually copied into the classes (without using traits, the "language-assisted copy & paste" feature).
What's so special about the constructor here? Shouldn't PHP be able to figure out that one of them overrides the other? I couldn't find anything about this limitation in the manual.
This related question mentions a way to get around the problem (by using aliases for trait methods), but not what's causing it in the first place.
Try what happens with the following code:
class A {
use T;
use T;
}
Because this is what you effectively wrote by extending from A and then using T again for B.
If you need to use trait T in base and subclasses, use it only in the base-class.
If you need it in subclasses only, use it only in the leaf subclasses.
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