The Final Keyword In PHP5

PHP5 allows you to stop classes being extended or to stop child classes overwriting functions.

The first way to use the final keyword is to stop child classes from overwriting functions when they are created. This can be used to stop an important function from being overwritten. To use the final keyword here just add it to the start of function name.

class ParentClass{
 final public function importantFunction() {
  echo 'ParentClass::importantFunction()';
 }
}
 
class ChildClass extends ParentClass{
 public function importantFunction() {
  echo 'ChildClass::importantFunction()';
 }
}
 
$child = new ChildClass();
$child->printString();

Attempting to override this function will produce the following error.

Fatal error: Cannot override final method ParentClass::importantFunction() in test.php on line 12

The second way to use the final keyword is to stop child classes from being created. This can be useful if you have a security class that you want to keep as the final version. To use the final keyword like this just append it to the class name.

final class ParentClass{
 public function importantFunction() {
  echo 'ParentClass::importantFunction()';
 }
}
 
class ChildClass extends ParentClass{
 public function importantFunction() {
  echo 'ChildClass::importantFunction()';
 }
}
 
$child = new ChildClass();
$child->printString();

Attempting to override this function will produce the following error.

Fatal error: Class ChildClass may not inherit from final class (ParentClass) in test.php on line 12

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
6 + 14 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.