- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Final keyword in PHP
- final keyword in Java
- Final keyword in C#
- final keyword in Dart Programming
- Explain final class and final method in PHP.
- Using final keyword to Prevent Overriding in Java
- PHP namespace keyword and __NAMESPACE__ constant
- What is "namespace" keyword in PHP?
- Can a final keyword alone be used to define a constant in Java?
- Final variable in Java
- Final class in Java
- Final Arrays in Java
- final variables in Java
- Final variables in C#
- Java static keyword

Advertisements