Recipe 7.5. Preventing Changes to Classes and Methods

7.5.1. Problem

You want to prevent another developer from redefining specific methods within a child class, or even from subclassing the entire class itself.

7.5.2. Solution

Label the particular methods or class as final:

final public function connect($server, $username, $password) {     // Method definition here }


final class MySQL {     // Class definition here }

7.5.3. Discussion

Inheritance is normally a good thing, but it can make sense to restrict it.

The best reason to declare a method final is that a real danger could arise if someone overrides it. For example, data corruption, a race condition, or a potential crash or deadlock from forgetting (or forgetting to release) a lock or a semaphore.

Another common reason to declare a method final is that the method is "perfect." When you believe there's no way to update the method to make it better, declare it using the final keyword. This prevents subclasses from ruining it by reimplementing the method in an inferior manner.

However, think hard before you choose final in this case. It's impossible to come up with all the reasons someone may need to override a method. If you're distributing a third-party library (such as a PEAR package), you will cause a real headache if you incorrectly mark a method as final.

Make a method final by placing the final keyword at the beginning of the method declaration, as shown in Example 7-12.

Defining a final method

final public function connect($server, $username, $password) {     // Method definition here }

This prevents someone from subclassing the class and creating a different connect( ) method.

To prevent subclassing of an entire class, don't mark each method final. Instead, make a final class as shown in Example 7-13.

Defining a final class

final class MySQL {     // Class definition here }

A final class cannot be subclassed. This differs from a class in which every method is final because that class can be extended and provided with additional methods, even if you cannot alter any of the preexisting methods.

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: