Skip to main content
Method overriding in PHP is an object-oriented programming mechanism where a subclass provides a specific implementation for a method that is already defined in its parent class. The overridden method in the child class must share the same name and a compatible signature with the parent method, effectively replacing the parent’s behavior during runtime via dynamic dispatch.

Signature Compatibility and Rules

When overriding a method, PHP enforces strict rules regarding the method signature to maintain the Liskov Substitution Principle (LSP):
  • Visibility: The access modifier of the overriding method must be the same or less restrictive than the parent method. For example, a protected method can be overridden as protected or public, but never as private.
  • Covariant Return Types: The child method can declare a return type that is narrower (more specific) than the parent method’s return type.
  • Contravariant Parameters: The child method can declare parameter types that are broader (less specific) than the parent method’s parameter types.
  • Additional Parameters: An overriding method is allowed to add new parameters to the signature, provided those new parameters have default values (i.e., they are strictly optional).
  • The final Keyword: If a parent method is prefixed with the final keyword, it is locked and cannot be overridden. Attempting to do so throws a fatal error.
  • Constructor Exemption: Constructors (__construct) are exempt from LSP signature compatibility rules. A child class can define a completely different constructor signature from its parent without throwing an error, unless the constructor is explicitly defined in an interface.

Accessing the Parent Method

Overriding a method completely shadows the parent’s implementation. In PHP, neither standard methods nor magic methods (such as __construct) implicitly invoke their parent counterparts. If the parent class’s logic is required, the developer must explicitly call the shadowed parent method from within the child class using the parent:: scope resolution operator.

Syntax Visualization

Tired of Poor PHP Skills? Fix That With Deep Grasping!Learn More