QUIZGUM

Coding Class

Quizgum : trait insteadof

Determine the name to use instead of the trait's methods

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.

How To Use insteadof

  1. trait trait name{}
  2. class class name
  3. {
  4. use trait name, trait name {
  5. The name of the trait to use :: method name insteadof the name of the trait to disable;
  6. }
  7. }

So let's look at an example..

  1. <?php
  2. trait apple
  3. {
  4. public function phone()
  5. {
  6. return 'iPhone';
  7. }
  8. }
  9.  
  10. trait samsung
  11. {
  12. public function phone()
  13. {
  14. return 'galaxy';
  15. }
  16. }
  17.  
  18. class disneyAnimation
  19. {
  20. use apple, samsung {
  21. apple::phone insteadof samsung;
  22. }
  23. }
  24.  
  25. $disney = new disneyAnimation;
  26. echo "Judith in zootopia ".$disney->phone()." Use it." ;
  27. ?>

If you have 3 traits, instead of, write the name of the trait you don't want to use.

insteadof multiple usage

  1. trait trait name{}
  2. class class name
  3. {
  4. use trait name, trait name {
  5. Use trade name ::method name insteadof not be used trade name, not be used trade name;
  6. }
  7. }

Try insteadof in multiples with the following example:

  1. <?php
  2. trait apple
  3. {
  4. public function phone()
  5. {
  6. return 'iPhone';
  7. }
  8. }
  9.  
  10. trait samsung
  11. {
  12. public function phone()
  13. {
  14. return 'galaxy';
  15. }
  16. }
  17.  
  18. trait lg
  19. {
  20. public function phone()
  21. {
  22. return 'g';
  23. }
  24. }
  25.  
  26. class disneyAnimation
  27. {
  28. use apple, samsung, lg {
  29. apple::phone insteadof samsung, lg;
  30. }
  31. }
  32.  
  33. $disney = new disneyAnimation;
  34. echo "Judith in zootopia ".$disney->phone()." Use it.";
  35. ?>

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.