← Back to Chapters

PHP OOP Overriding Properties & Methods

? PHP OOP Overriding Properties & Methods

? Quick Overview

Overriding in PHP Object-Oriented Programming allows child classes to redefine properties and methods inherited from parent classes. This enables flexible behavior and supports polymorphism.

? Key Concepts

  • Child class replaces parent method logic
  • Property values can be redefined
  • Method signatures must remain compatible
  • parent:: can access original behavior

? Syntax / Theory

When a child class defines a method or property with the same name as its parent, PHP uses the child version during runtime. This makes behavior customizable without changing base classes.

? Code Example

? View Code Example
// Parent class definition
<?php
class ParentClass {
public $name = "Parent";

public function greet() {
echo "Hello from Parent!";
}
}

// Child class overriding property and method
class ChildClass extends ParentClass {
public $name = "Child";

public function greet() {
echo "Hello from Child!";
}
}

// Creating object of child class
$child = new ChildClass();
echo $child->name;
$child->greet();
?>

? Live Output / Explanation

The output displays Child as the property value and prints the child class greeting message. PHP prioritizes the overridden definitions in the child class.

? Interactive Concept

Imagine a blueprint system where the base design is reused, but details are customized per requirement — overriding works the same way in OOP.

? Use Cases

  • Customizing behavior in frameworks
  • Extending base classes safely
  • Implementing polymorphism
  • Code reuse with flexibility

? Tips & Best Practices

  • Use parent::method() when extending logic
  • Keep method signatures identical
  • Prefer protected over public when possible
  • Document overridden methods clearly
  • Avoid overriding without understanding base logic

? Try It Yourself

  • Create a Vehicle class and override start() in Car
  • Override a property value and test access
  • Use parent:: inside an overridden method
  • Experiment with protected methods
  • Build a banking interest calculator using overriding