what is final keyword?

  • final is a predefined keyword in php.
  • Final keyword is used with class, variable, and function.
  • If a class is declared as final then that class can’t be inherited by other class. A final class is a class that cannot be extended. To declare a class as final, you need to prefix the ‘class’ keyword with ‘final’.
  • BaseClass is declared as final and hence cannot be extended (inherited). DerivedClass tries to extend from BaseClass and hence the compiler will throw a compile error.
  • If a method is declared as final then that method is can’t be override.
  • Note: We can not declare variables as Final in PHP.
  • <?php
    final class BaseClass {
    public function myMethod() {
    echo "BaseClass method called";
    }
    }
    //this will cause Compile error
    class DerivedClass extends BaseClass {
    public function myMethod() {
    echo "DerivedClass method called";
    }
    }
    $obj = new DerivedClass();
    $obj->myMethod();
    ?>
    ( ! ) Fatal error: Class DerivedClass may not inherit from final class (BaseClass) in D:\wamp\www\OOPs\index.php on line 13


    Final method

    A final method is a method that cannot be overridden. To declare a method as final, you need to prefix the function name with the ‘final’ keyword.

    <?php
    class BaseClass {
    final public function myMethod() {
    echo "BaseClass method called";
    }
    }
    class DerivedClass extends BaseClass {
    //this will cause Compile error
    public function myMethod() {
    echo "DerivedClass method called";
    }
    }
    $c = new DerivedClass();
    $c->myMethod();
    ?>

    ( ! ) Fatal error: Cannot override final method BaseClass::myMethod() in D:\wamp\www\OOPs\index.php on line 13

    DerivedClass extends from BaseClass. BaseClass has the method myMethod() declared as final and this cannot be overridden. In this case the compiler causes a compile error.





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here