If you have two traits and two traits have a method with the same name, you can specify which one to use.
The keyword insteadof to specify which method to use.
- trait trait name{}
- class class name
- {
- use trait name, trait name {
- The name of the trait to use :: method name insteadof the name of the trait to disable;
- }
- }
So let's look at an example..
- <?php
- trait apple
- {
- public function phone()
- {
- return 'iPhone';
- }
- }
- trait samsung
- {
- public function phone()
- {
- return 'galaxy';
- }
- }
- class disneyAnimation
- {
- use apple, samsung {
- apple::phone insteadof samsung;
- }
- }
- $disney = new disneyAnimation;
- echo "Judith in zootopia ".$disney->phone()." Use it." ;
- ?>
If you have 3 traits, instead of, write the name of the trait you don't want to use.
- trait trait name{}
- class class name
- {
- use trait name, trait name {
- Use trade name ::method name insteadof not be used trade name, not be used trade name;
- }
- }
Try insteadof in multiples with the following example:
- <?php
- trait apple
- {
- public function phone()
- {
- return 'iPhone';
- }
- }
- trait samsung
- {
- public function phone()
- {
- return 'galaxy';
- }
- }
- trait lg
- {
- public function phone()
- {
- return 'g';
- }
- }
- class disneyAnimation
- {
- use apple, samsung, lg {
- apple::phone insteadof samsung, lg;
- }
- }
- $disney = new disneyAnimation;
- echo "Judith in zootopia ".$disney->phone()." Use it.";
- ?>
What if you also need to use the phone() method from another trait?
Next time, we'll learn how to use the methods of the same name in different traits.