Does the use of traits replace the role of multiple inheritance?

Asked

Viewed 1,010 times

4

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

2 answers

7


In a way yes. Not entirely because a trait can not have been. But you can get subtype and subclass of various types with it.

Name conflicts

If the class has an implementation of the method it will be considered and the implementations of the traits will be disregarded. The same applies if the trait has no implementation. Obviously the class is required to implement, unless another trait provide a conceptually acceptable implementation.

When there is a conflict an error is generated and the code does not work. It is possible to resolve the conflict and allow the correct functioning. Documentation shows how it is solved:

trait A {
    public function smallTalk() {
        echo 'a';
    }
    public function bigTalk() {
        echo 'A';
    }
}

trait B {
    public function smallTalk() {
        echo 'b';
    }
    public function bigTalk() {
        echo 'B';
    }
}

class Talker {
    use A, B {
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
    }
}

class Aliased_Talker {
    use A, B {
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
        B::bigTalk as talk;
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

So there’s a syntax that determines which of the traits ambiguous should be used in each situation. In this example the smallTalk() used will be from trait B. Already the bigTalk() will be of A. And if you use a ninth method called talk() which will be the same as calling the bigTalk() of B. The smallTalk() of A is not accessible.

2

Suppose you have two or more classes that need to use a common method, it may be possible to use Traits.

Traits are mechanisms that help in code reuse, and serve perfectly to solve the problem of multiple inheritance failure, as PHP does not support multiple inheritance. Traits was released as of PHP version 5.4.0.

A trait cannot be instantiated or have its methods called directly and must be incorporated into a class. The syntax for embedding a trait in a class is through the reserved word use.

class Base {
        public function sayStack() {
            echo 'Stack ';
        }
    }

    trait SayOverflow {
        public function sayOverflow() {
            parent::sayStack();
            echo 'Overflow!';
        }
    }

    class MyStackOverflow extends Base {
        use SayOverflow;
    }

    $o = new MyStackOverflow();
    $o->sayOverflow();

References:
Documentation php.net
When to use Inheritance, Abstract Class, Interface or a Trait?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.