PHP Tutorial
PHP Flow Control
PHP Functions
PHP String
PHP Array
PHP Date Time
PHP Object Oriented
Regular Expression
PHP Cookie & Session
PHP Error & Exception handling
MySQL in PHP
PHP File Directory
PHP Image Processing
In PHP, the final
keyword is used to prevent class inheritance (when applied to a class) and to prevent method overriding (when applied to a method).
Final Classes
When a class is declared as final
, it cannot be extended by other classes. Here's an example:
final class FinalClass { // Class properties and methods go here } class SomeClass extends FinalClass { // Results in Fatal error: Class SomeClass may not inherit from final class (FinalClass) }
In this example, because FinalClass
is declared as final
, trying to extend it in SomeClass
results in a fatal error.
Final Methods
When a method in a class is declared as final
, it cannot be overridden in a child class. Here's an example:
class ParentClass { final public function myMethod() { echo 'Parent'; } } class ChildClass extends ParentClass { public function myMethod() { // Results in Fatal error: Cannot override final method ParentClass::myMethod() echo 'Child'; } }
In this example, because myMethod()
in ParentClass
is declared as final
, trying to override it in ChildClass
results in a fatal error.
The final
keyword is useful when you want to ensure that a class maintains its original behavior, and is not extended or modified by any other class. Similarly, marking a method as final
ensures that any classes extending the parent class will use the parent method as-is, without any modifications.
Remember that using final
increases rigidity, as it prevents other developers from extending your classes or methods. It should be used judiciously and only when necessary.
When to use final classes in PHP:
<?php final class MyFinalClass { // Class implementation }
Benefits of using final methods in PHP:
<?php class ParentClass { final public function myFinalMethod() { // Method implementation } } class ChildClass extends ParentClass { // Attempting to override myFinalMethod will result in an error }
Examples of PHP final classes and methods:
<?php final class MyFinalClass { // Class implementation }
<?php class ParentClass { final public function myFinalMethod() { // Method implementation } }
Overriding and extending final methods in PHP:
<?php class ParentClass { final public function myFinalMethod() { // Method implementation } } class ChildClass extends ParentClass { // Attempting to override myFinalMethod will result in an error }
PHP inheritance with final classes and methods:
<?php final class MyFinalClass { final public function myFinalMethod() { // Method implementation } }