PHP Classes and Objects Preventing Changes to Classes and Methods - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Classes and Objects Preventing Changes to Classes and Methods - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Saturday, May 25, 2019

PHP Classes and Objects Preventing Changes to Classes and Methods

PHP Classes and Objects




Preventing Changes to Classes and Methods

Problem

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

Solution

Label the particular methods or class as final:

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

and:

           final class MySQL {
                  // Class definition here
           }

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.

Make a method final by placing the final keyword at the beginning of the method declaration:

           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:

           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.



No comments:

Post a Comment

Post Top Ad