问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/39820753/how-does-insteadof-keyword-in-a-trait-work