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

final class class name{}

So let's look at an example.

<?php

    final class GoogleCar
    {

    }

    class Car extends GoogleCar
    {
        public function hello()
        {
            return 'hello';
        }
    }
    $ever = new Car;
    echo $ever->hello();

?>

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.

<?php

    class GoogleCar
    {

    }

    class Car extends GoogleCar
    {
        public function hello()
        {
            return 'hello';
        }
    }
    $ever = new Car;
    echo $ever->hello();

?>

Result

Thank you.