FINAL KEYWORD IN PHP Here Is What You Should Know About

FINAL KEYWORD IN PHP Here Is What You Should Know About

FINAL KEYWORD IN PHP Here Is What You Should Know About

The FINAL KEYWORD was introduced in PHP 5, and unlike other programming languages like JAVA, in PHP FINAL KEYWORD is only applicable to CLASS AND METHODS.

What is the role of FINAL keyword when used with CLASS and METHOD?

If we use FINAL keyword along with a CLASS, that class cannot be inherited. And when used with METHOD, it cannot be overridden.

In order to under this let’s consider some cases with the following examples:

Case One: When neither CLASS is FINAL nor METHOD is FINAL –

<?php
class first{
public function one(){
echo "Hello From Class One";
}
}
class second extends first{
public function one(){
echo "Hello From Class Two";
}
}

$two = new second();
$two->one();

OUPUT –

Output one for final keyword in php
Output when class in not final

Explanation – In case one neither CLASS nor METHOD is FINAL, so the class can be inherited and METHOD can be overridden, hence we are getting the output as – “Hello From Class Two”.

Case Two: When CLASS is FINAL but METHOD is not FINAL and we are not trying to override METHOD

<?php
final class first{
public function one(){
echo "Hello From Class One";
}
}
class second extends first{
}

$two = new second();
$two->one();
FINAL KEYWORD IN PHP when class is final

OUTPUT –

Explanation – In case two when CLASS is FINAL but METHOD is not FINAL, and we are not overriding METHOD so we get an error stating “FINAL CLASS cannot be inherited i.e Class second cannot inherit Class one”.

Case Three: When CLASS is not FINAL but METHOD is FINAL and we are trying to override METHOD :

<?php
class first{
final public function one(){
echo "Hello From Class One";
}
}
class second extends first{
public function one(){
echo "Hello From Class Two";
}
}

$two = new second();
$two->one();

OUPUT –

Explanation – In case three CLASS is not FINAL but METHOD is FINAL, and we are overriding METHOD so we get an error stating “Cannot Override Final Method first::one()” as in this case we are not allowed to override the final method of class one which is our base class.

CONCLUSION

After testing above three cases we can conclude that:

A FINAL CLASS cannot be inherited.

A FINAL METHOD cannot be overridden.

Note: All the above code was tested using the following tools:

  1. PHP Server – XAMPP
  2. Text/Code Editor – NOTEPAD++
  3. Browser – Google Chrome.

You can use any browser any operating system to test your results.

Share this Post:

Related Posts: