CLASS web

PHP

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();

?>

I'll check the results right below.







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();

?>

I'll check the results right below.







Result

Thank you.





ALL COMMENTS 0

Sort by

PinkCoding

PinkCoding

X

PinkCoding

Web Scratch Pad

X

loading

            
            
        

Back to the course