PHP Final Class - php website - Phptpoint.com

PHP Final Class

/ins>

Use of final class in PHP

The final keyword prevents child classes from overriding a method by prefixing the definition with final.

It means if we define a method with final then it prevent us to override the method.

Output
Fatal error: Cannot override final method A::show() in C:xampplitehtdocs1aa.php on line 18

In the above example
The class A which is my parent class.
In which show method is marked by final. It means that show method can not override in any it’s child class.
To see the error class B define which is extended by A. It means B is the child class of A.
In B it is try to define the final method (show) in class B.
Which will produce the fetal error with message “Cannot override final method A::show()”.
It means we can not define final method of parent class in it’s child class.

Final use before the class

If the class itself is being defined final then it can’t be extended.

It means when we define a class with final then it will not allow to define it’s child class.

Output
Fatal error: Class B may not inherit from final class (A) in C:xampplitehtdocs1aa.php on line 17

In the above example
class A define with final. It mean this class can not be extended.
When class B defined with extend A ( which means B is the child class of A).
But It produce the error with message “Class B may not inherit from final class (A)” .
It means that it will not allow to create any child class of A.
It means that final class can not be inherited.