CHAPTER 3 – final METHODS
3.15 final METHODS Until now, you have seen that when you extend a class (or inherit from a class), you may override inherited methods with a new implementation. How- ever, there are times where you might want to make sure that a method can- not be re-implemented in its derived classes. For this purpose, PHP supports the Java-like final access modifier for methods that declares the method as the final version, which can't be overridden. The following example is not a valid PHP script because it is trying to override a final method: class MyBaseClass { final function idGenerator() { return $this->id++; } protected $id = 0; } class MyConcreteClass extends MyBaseClass { function idGenerator() { return $this->id += 2; } }
This script won't work because by defining idGenerator() as final in MyBaseClass, it disallows the deriving classes to override it and change the behavior of the id generation logic.