The final Keyword in PHP

The final keyword is related to inheritance concept in object-oriented programming (OOP). Inheritance is a process when a child class inherits properties and behavior from the parent class. The final keyword can be applied on classes and class methods.

Final class

When a class is declared as final it cannot be inherited.

Let’s say we have two classes. AlaskanMalamute class extends Pomsky class which declared as final.

Pomsky.php

<?php

final class Pomsky {}

AlaskanMalamute.php

<?php

class AlaskanMalamute extends Pomsky {}

Then create an object of a AlaskanMalamute class and run the following code:

<?php

require_once 'Pomsky.php';
require_once 'AlaskanMalamute.php';

$dog = new AlaskanMalamute();

The code gives a fatal error:

Fatal error: Class AlaskanMalamute may not inherit from final class (Pomsky) in AlaskanMalamute.php on line 3

Final method

When a method is declared as final in parent class then this method cannot be overridden by the child class.

We have two classes. SiberianHusky class extends Dog class and overrides the makeSound method which declared as final.

Dog.php

<?php

class Dog
{
    final public function makeSound(): void
    {
        echo 'Woof';
    }
}

SiberianHusky.php

<?php

class SiberianHusky extends Dog
{
    public function makeSound(): void
    {
        echo 'Woof!!!';
    }
}

Run the following code:

<?php

require_once 'Dog.php';
require_once 'SiberianHusky.php';

$dog = new SiberianHusky();

The code gives a fatal error:

Fatal error: Cannot override final method Dog::makeSound() in SiberianHusky.php on line 5

Leave a Comment

Your email address will not be published. Required fields are marked *