final keyword in PHP

final keyword is used in PHP as final class and final method. A final class is one which cannot be extended. A final method cannot be overridden in extended class.

usages: Database class, configuration class etc.

Example #1 Final methods example

<?php
 class BaseClass {
    public function test() {
        echo "BaseClass::test() called\n";
    }
    
    final public function moreTesting() {
        echo "BaseClass::moreTesting() called\n";
    }
 }

class ChildClass extends BaseClass {
    public function moreTesting() {
        echo "ChildClass::moreTesting() called\n";
    }
 }
 // Results in Fatal error: Cannot override final method BaseClass::moreTesting()
 ?>

Example #2 Final class example

<?php
 final class BaseClass {
    public function test() {
        echo "BaseClass::test() called\n";
    }

   // Here it doesn't matter if you specify the function as final or not
    final public function moreTesting() {
        echo "BaseClass::moreTesting() called\n";
    }
 }

class ChildClass extends BaseClass {
 }
 // Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass)
 ?>

Leave a Comment

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