4.6. Preventing Changes to a Class or Method

You might want a class to be used exactly as you have written it. You can prevent the creation of a child class that changes the implementation of methods with the final keyword, as follows:

final class classname

When a class is defined as final, a child class can't be created. You can also define a method as final, as follows:

final public moveForward()

If a child class includes a method with the same name as a final method in the parent class, an error message is displayed, similar to the following:

Fatal error: Cannot override final method Car::moveForward()

In this case, the parent class Car includes a method moveForward that is defined as final. The child class Sedan extends Car. However, the Sedan class defines a method moveForward, a method with the same name as a final method in the parent Car class. This isn't allowed.

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.