What is use of final keyword in PHP?

use of final keyword in php

When we hear the final word then at the very first glance we come up with one sentence only. “THIS IS FINAL. THAT’S IT”. Well, in programming also it means the same. We decide to make a particular operation as final. Simple, isn’t it? Let’s explore use of final keyword in PHP in depth.

In Object-Oriented Concept, inheritance allows flexibility to extend a class. We can create multiple sub-classes to extend the functionality of a parent class. But PHP also allows to stop the extension of the class. Such a class is called final class.

Final keyword is used to make a particular class OR method as concrete. This means, particular class OR object is prevented from making any new change in it and further change in the behavior is restricted.

PHP has adopted an objected-oriented concept in version 5, where apart from other OOPs concept (like abstract, magic methods, interfaces, cloning, and type-hinting), final classes and methods were also introduced.

Let’s start understanding final keyword step by step.

How to use final keyword in PHP?

Final keyword in PHP is used only for classes and methods. When we need to use final keyword to class then we just need to prefix class name with final keyword and for a method as well we need to do the same step by prefixing method name as final.

Let’s understand the use of final keyword using an example-
Using final with class

<?php
// example 1
final class classA {
    
    public function methodA(){
        // code
    }

}

Using final with method

<?php
// example 2
class classA {
    
    public final function methodA(){
        // code
    }

}

In the above examples, we first defined class classA as final which means now all the properties and methods are final and in the second example methodA is final which means now only methodA is final.

Why do we need to use of final keyword in PHP?

When we make a class/method as final then we need to confirm this class /object will never be open to be overridden. It means by no ways there will be any change in it.

This is mainly for the security season because there are sometimes a situation in the project where we need to make sure that there should be no more inheritance for a particular class/method.

To summarize-

When to use Final in PHP?

As seen above, when we want to avoid further extension of class/method then we can use final keyword for this purpose. But we can use final keyword only when we want to avoid further extension of class/member by inheritance way.

Understanding PHP final classes with example-

In the above examples, we saw how we can make a class and method as final.

For stronger protection, we can also define a class as final which makes it uninheritable and method as private which will add extra security and will make sure that respective function call only be accessed by its member functions
Take a look at this script-

  • Defining methods as private along with final class
<?php

final class animal{

    public $name = '';

    private function walk(){
        return 'I walk';
    }
}

$obj = new animal();
echo $obj->walk();  
// Fatal error: Uncaught Error: Call to private method animal::walk() from context '' in file.php
<?php

final class animal{

    public $name = '';

    public function walk(){
        return 'I walk';
    }
}

class dog extends animal{

   public $name = '';
   
    public function bark() {
            return 'I bark';
        }
}

echo (new dog())->walk();
// Fatal error: Class dog may not inherit from final class (animal) in file.php on line 19
  • No sense of making method as final when class is defined as final.
<?php

final class animal{

    public $name = '';

    final public function walk(){
        return 'I walk';
    }
}

There is absolutely no reason to make method as final when class inself defined as final. This is because once class is final then its all the properties and methods becomes final as well.

  • Defining class constructor as final
<?php

class animal{

    public $name = '';

    final public function __construct(){
        return 'I walk';
    }
}

Yes, we can define constructor of the class as final but as per final keyword property now sub-classes will not have __construct() method in the sub-classes, and as we all know that Parent constructors are never called automatically. We still require to call parent::__construct() in the child class constructor.

But PHP has still kept its old style of defining class constructor by className(). This way we can override parent class method.

  • Can not define class properties as final
<?php

class animal {
    final public $id;
}

var_dump(new animal);
// OUTPUT

Fatal error: Cannot declare property animal::$id final, the final modifier is allowed only for methods and classes in file.php on line 4

We got above Fatal error because final and static keyword is not allowed to use together for properties only. Because final keyword does not allow that property to be inherited and a static keyword is used to make that property value available for all the objects.

Conclusion-

Use of final keyword in php can be done carefully and added whenever required. PHPs object oriented is quite late but we need to keep in mind that we can make class as a final whenever we feel that this class should never be extended. This will prevent unnecessary inheritance hierarchy.