Learn PHP Tutorial

PHP OOP – Final Method and Final Class


In PHP, final keyword is used to create final method or final class.

A final method cannot be overridden in the child class.

A final class cannot be inherited. It means we cannot create sub class of a final class.

Syntax:

<?php
class Father
{
    final function display($number)
    {
        echo "Super Class.";
    }
}

?>

If we try to override the final method in child class. It will show error “Cannot override the final method”.

Please look at the below example. It will show errors due to overriding a final method in sub-class.

<?php
class Father
{
    final function display($number)
    {
        echo "Super Class.";
    }
}

class Son extends Father{
    function display()
    {
        echo "Son Class.";
    }
}

?>

If we use final keyword with a class, and inherit with a child class. It will show an error :

Fatal error: Class Son may not inherit from final class(Father) in ….

<?php
final class Father
{
    final function display($number)
    {
        echo "Super Class.";
    }
}

class Son extends Father{
    function display()
    {
        echo "Son Class.";
    }
}

?>