PHP Final Keyword


 

PHP Final Keyword

In this current tutorial we will study about final keyword, final keyword helps us to put some constraint on classes and it's methods. Using final keyword a class can not be inherited and a method can not be overridden.

In this current tutorial we will study about final keyword, final keyword helps us to put some constraint on classes and it's methods. Using final keyword a class can not be inherited and a method can not be overridden.

Final Keyword in PHP:

If you are familiar with Java then you must know the functionality of Final keyword. Final keyword prevents child classes from overriding a method of super or parent class. If we declare a class as final then it could not have any child class that means no class can inherit the property of this class.

PHP Final Keyword Example:

<?php

class A

{

final public function disp(){

echo "Inside the final function";

}

}

class B extends A

{

function disp(){

echo "Inside the final function";

}

}

$obj=new B();

$obj->disp();

?> 

Output:

Fatal error: Cannot override final method A::disp() in C:\xampp\htdocs\PHP-AJAX\final.php on line 14
Example:

<?php

final class A

{

public function disp(){

echo "Inside the final function";

}

}

class B extends A

{

function disp(){

0

echo "Inside the final function";

}

}

1

$obj=new B();

$obj->disp();

?>

2
Output:

Fatal error: Class B may not inherit from final class (A) in C:\xampp\htdocs\PHP-AJAX\final.php on line 14

Ads