Friday, 10 August 2018

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.
  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

0 comments:

Post a Comment