Dimi Antoni Vargas
Dimi Antoni Vargas

Reputation: 127

The use of traits replace the role of multiple inheritance no PHP?

What happens if I use a class in two different traits, and both have a method with the same name but different implementations of this method?

Upvotes: 0

Views: 170

Answers (1)

BVengerov
BVengerov

Reputation: 3007

Short answer

enter image description here (c) AbraCadaver

Long answer

Say you have a class Foo that uses traits A and B:

class Foo {
    use A, B;
}

Where both traits have a method with a similar name, but different implementation (the implementation doesn't matter, really):

trait A {
    public function bar() {
        return true;
    }
}

trait B {
    public function bar() {
        return false;
    }

Traits work by extending the class horizontally. Simply put - just adding any new contents to the class. And all works fine till there's any doubling in trait methods and properties. Then you have yourself a fatal error if this conflict is not explicitly resolved.

The sweet part is, you can resolve this conflict by specifying which method from which trait to use:

class Foo {
    use A, B {
        B::bar insteadof A;
    }
}

You can also save the other method from oblivion by using alias for it:

class Foo {
    use A, B {
        B::bar insteadof A;
        A::bar as barOfA;
    }
}

The manual has traits farely well documented, go check it out.

Upvotes: 2

Related Questions