QUIZGUM

Coding Class

Quizgum : trait abstract

Assigning Rules to Traits

You can specify a method that must be declared in the class that uses the trait.
Same thing with the abstract keyword.

How To Use abstract for trait methods

  1. trait traitname{
  2. abstract access modifier function method name();
  3. }

So let's look at an example.

  1. <?php
  2. trait apple
  3. {
  4. // must declare likeApple() method
  5. abstract static function likeApple();
  6.  
  7. public static function phone()
  8. {
  9. return 'iPhone';
  10. }
  11. }
  12.  
  13. class disney
  14. {
  15. use apple;
  16. }
  17.  
  18. $disney = new disney;
  19. ?>

Result

The error occurs because you do not declare the likeApple method in the disney class. The following example declares the likeApple() method.

  1. <?php
  2. trait apple
  3. {
  4. //must declare likeApple() method
  5. abstract static function likeApple();
  6.  
  7. public static function phone()
  8. {
  9. return 'iPhone';
  10. }
  11. }
  12.  
  13. class disney
  14. {
  15. use apple;
  16.  
  17. public function likeApple()
  18. {
  19. return 'Disney and Apple are friendly.';
  20. }
  21. }
  22.  
  23. $disney = new disney;
  24. echo $disney->likeApple();
  25. ?>

Result

We have seen how to use this abstract to create method rules in a trait. ^-^ *