- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
PHP final Keyword
Introduction
Using final keyword in the definition of an instance method in a PHP class prevents it from being overridden by child class. Similarly, if final is used in definition of class itself, such a class cannot be extended.
Syntax
final class myclass {} class myclass{ final method mymethod(){} }
final method example
In following example, attempt tooverride final method results in error
Example
<?php class parentclass{ final function test(){ echo "final method in parent class"; } } class childclass extends parentclass{ function test(){ echo "overriding final method in parent class"; } } $obj=new childclass(); $obj->test(); ?>
Output
Output shows following error message
PHP Fatal error: Cannot override final method parentclass::test() in line 16
final class example
Similarly a final class can't be inherited from as following example shows
Example
<?php final class parentclass{ final function test(){ echo "final method in parent class"; } } class childclass extends parentclass{ function test(){ echo "overriding final method in parent class"; } } $obj=new childclass(); $obj->test(); ?>
Output
Output shows following error message
PHP Fatal error: Class childclass may not inherit from final class (parentclass) in line 16
Advertisements