Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can constructor definitions from traits collide?

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.

like image 918
Zilk Avatar asked Oct 21 '22 02:10

Zilk


1 Answers

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.

like image 191
hakre Avatar answered Oct 27 '22 10:10

hakre