How to create final classes and methods

How to prevent a method from being overridden

A class with a final method

      class Person {
        // Other properties and methods not shown here 
        
        final public function getFirstName() {
          return $this->firstName; 
        } 
      }
      

A subclass that attempts to override a final method leading to a fatal error

      class Employee extends Person {
        // Other properties and methods not shown here

        // This method attempts to override a final method - fatal error 
        public function getFirstName() {
          return ucwords($this->firstName); 
        } 
      }
      

How to prevent a class from being inherited

A final class

      final class Employee extends Person {
        // Properties and methods for class 
      }
      

A class that attempts to inherit a final class leading to a fatal error

      class PartTime extends Employee {
        // Properties and methods for class 
      }
      

Description

Back