The final Keyword in PHP

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 to classes, class methods and constants.

Final class

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

Let's say we have two classes. AlaskanMalamute class extends the 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 the 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

Final constant

Since PHP 8.1, we can use final constants. If constant is declared as final in the parent class, constant cannot be overridden by the child class.

We declared two classes, where Akita class extends Dog class. Akita class overrides the LEGS constant which declared as final in parent class.

Dog.php

<?php

class Dog
{
    final public const LEGS = 4;
}

Akita.php

<?php

class Akita extends Dog
{
    public const LEGS = 2;
}

Run the following code:

<?php

require_once 'Dog.php';
require_once 'Akita.php';

$dog = new Akita();

You will get a fatal error:

Fatal error: Akita::LEGS cannot override final constant Dog::LEGS in ...

Leave a Comment

Cancel reply

Your email address will not be published.