The Final Keyword In PHP5

14th April 2008

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.

  1. class ParentClass{
  2. final public function importantFunction() {
  3. echo 'ParentClass::importantFunction()';
  4. }
  5. }
  6.  
  7. class ChildClass extends ParentClass{
  8. public function importantFunction() {
  9. echo 'ChildClass::importantFunction()';
  10. }
  11. }
  12.  
  13. $child = new ChildClass();
  14. $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.

  1. final class ParentClass{
  2. public function importantFunction() {
  3. echo 'ParentClass::importantFunction()';
  4. }
  5. }
  6.  
  7. class ChildClass extends ParentClass{
  8. public function importantFunction() {
  9. echo 'ChildClass::importantFunction()';
  10. }
  11. }
  12.  
  13. $child = new ChildClass();
  14. $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.