Search This Blog

May 26, 2012

How to use Final Keyword on PHP OOP

As the word "final" signify itself, adding this prefix to your method or class signify that it can't be overridden. For methods that have "final" prefix will thrown a fatal error when you're trying to create the same object in your class. Furthermore, classes that have "final" prefix cannot be extended.

Here are the following examples:

Method with final Keyword:



<?php
class MyParentClass {
   public function test() {
       echo "ParentClass::test() called\n";
   }
   
   final public function anotherTesting() {
       echo "BaseClass::anotherTesting() called\n";
   }
}

class MyChildClass extends MyParentClass {
   public function anotherTesting() {
       echo "ChildClass::moreTesting() called\n";
   }
}
// Results in Fatal error: Cannot override final method MyChildClass::anotherTesting()

?> 


Class with final Keyword:

<?php
final class MyParentClass {
   public function test() {
       echo "ParentClass::test() called\n";
   }
   
   final public function anotherTesting() {
       echo "BaseClass::anotherTesting() called\n";
   }
}

class MyChildClass extends MyParentClass {
   public function anotherTesting() {
       echo "ChildClass::moreTesting() called\n";
   }
}
// Results in Fatal error: Class MyChildClass may not inherit from final class (MyParentClass)
?>


As you can see in the two examples above, both method and class can’t be overridden by its subclass. Doing so will throw an exception error and will break your code.

0 comments: