Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does insteadof keyword in a Trait work

Tags:

php

traits

I was just reading about traits and how multiple php traits can be used in the same php code separated by commas. I do not however understand the concept of the insteadof keyword that is used to resolve conflict in case two traits have the same function. Can anyone please explain how insteadof keyword works and how to use it to tell the engine that I am willing to use function hello() of trait A instead of that of trait B, given there are two traits A and B and a function hello() in both the traits.

like image 383
Kushagra Avatar asked Oct 02 '16 19:10

Kushagra


People also ask

Can a trait have a constructor PHP?

Unlike traits in Scala, traits in PHP can have a constructor but it must be declared public (an error will be thrown if is private or protected). Anyway, be cautious when using constructors in traits, though, because it may lead to unintended collisions in the composing classes.

Is trait a PHP keyword?

Definition and UsageThe trait keyword is used to create traits. Traits are a way to allow classes to inherit multiple behaviours.

How do traits work in PHP?

Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).


1 Answers

Explanation

According to Traits Documentation, when you have same method in multiple trait, then you can explicitly guide the program to use method of specific trait by the use of insteadof operator. Refer to the example below which has been borrowed from above link, Here, when $t->smallTalk() is invoked it calls the smallTalk method in trait B insteadof trait A which is exactly the insteadof operator has been used for here. Since Class Talker uses trait A, B and both traits have smallTalk() method, we explicitly tell it to use trait B's smallTalk.

Example

<?php
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;
    }
}

$t = new Talker;
$t->smallTalk();
$t->bigTalk();

Output

bA

I hope this has cleared your confusion.

like image 105
Samundra Avatar answered Oct 06 '22 19:10

Samundra