QUIZGUM

Coding Class

Quizgum : Prevent class inheritance

Prevent Extends

In the previous section, we learned how to disable overriding. I used the final keyword before the accessor of the method that would prevent overriding Using final when declaring a class prevents inheritance.

How to use final in a class

  1. final class class name{}

So let's look at an example.

  1. <?php
  2.  
  3. final class GoogleCar
  4. {
  5.  
  6. }
  7.  
  8. class Car extends GoogleCar
  9. {
  10. public function hello()
  11. {
  12. return 'hello';
  13. }
  14. }
  15. $ever = new Car;
  16. echo $ever->hello();
  17.  
  18. ?>

The code above does not allow you to inherit GoogleCar using final.
But Car class is inheriting.
So I get an error
Result of the code above

Result

Clearing final in the code above allows inheritance, so no error occurs.

  1. <?php
  2.  
  3. class GoogleCar
  4. {
  5.  
  6. }
  7.  
  8. class Car extends GoogleCar
  9. {
  10. public function hello()
  11. {
  12. return 'hello';
  13. }
  14. }
  15. $ever = new Car;
  16. echo $ever->hello();
  17.  
  18. ?>

Result

Thank you.