PHP extends Keyword

PHP

PHP extends Keyword - Class Inheritance

The extends keyword in PHP is a powerful feature used to create child classes that inherit properties and methods from a parent class. This mechanism, known as class inheritance, promotes code reuse, improves maintainability, and allows developers to build more complex and scalable applications by extending existing class functionality.

Prerequisites

  • Basic understanding of PHP syntax and object-oriented programming (OOP) concepts.
  • Familiarity with PHP classes, properties, and methods.
  • A development environment with PHP installed (version 5 or higher recommended).

Setup Steps

  1. Ensure PHP is installed on your system (run php -v in the terminal to check).
  2. Create a PHP file to define parent and child classes.
  3. Use a text editor or IDE that supports PHP (e.g., VSCode, PhpStorm).

Understanding the extends Keyword

In PHP, extends is used to declare that a class is inheriting from another class. The child class gains access to all public and protected properties and methods of the parent class, allowing you to reuse and override functionality as needed.

Basic Example of Class Inheritance with extends

<?php
class Vehicle {
    public $brand;

    public function __construct($brand) {
        $this->brand = $brand;
    }

    public function honk() {
        return "Beep! Beep!";
    }
}

// Car inherits from Vehicle using extends
class Car extends Vehicle {
    public $model;

    public function __construct($brand, $model) {
        parent::__construct($brand); // Call parent constructor
        $this->model = $model;
    }

    public function getInfo() {
        return "This car is a " . $this->brand . " " . $this->model . ".";
    }
}

$car = new Car("Toyota", "Corolla");
echo $car->honk();      // Output: Beep! Beep!
echo "\n";
echo $car->getInfo();   // Output: This car is a Toyota Corolla.
?>

Explanation of the Example

  • Vehicle is the parent class with a property $brand and method honk().
  • Car is the child class extending Vehicle using the extends keyword.
  • The child class constructor calls the parent constructor with parent::__construct($brand); to initialize inherited properties.
  • Car adds its own property $model and method getInfo().
  • Objects of the child class can access both parent and child properties/methods.

Advanced Example: Overriding Parent Methods

<?php
class Vehicle {
    public function startEngine() {
        return "Starting engine...";
    }
}

class Car extends Vehicle {
    // Overriding startEngine method
    public function startEngine() {
        return "Starting car engine with key...";
    }
}

$vehicle = new Vehicle();
$car = new Car();

echo $vehicle->startEngine(); // Output: Starting engine...
echo "\n";
echo $car->startEngine();     // Output: Starting car engine with key...
?>

Best Practices for Using the extends Keyword

  • Use inheritance when there is a clear โ€œis-aโ€ relationship between classes (e.g., Car is a Vehicle).
  • Always call the parent constructor from the child constructor if the parent has initialization logic.
  • Prefer to keep inheritance hierarchies shallow and avoid deep class chains for better maintainability.
  • Use protected visibility for properties and methods that should be accessible to child classes but not publicly.
  • Override parent methods carefully and call parent::methodName() if you want to preserve base functionality.

Common Mistakes When Using extends

  • Trying to inherit from multiple classes - PHP supports only single inheritance.
  • Not calling the parent constructor when overriding constructor in child class, leading to uninitialized properties.
  • Making parent properties private if child classes need to access or override them (use protected instead).
  • Overriding methods but forgetting to respect method signatures (parameters), causing errors.
  • Using inheritance for code reuse when composition might be a better design choice.

Interview Questions

Junior-Level Interview Questions

  • What does the extends keyword do in PHP?
    It allows a class (child) to inherit properties and methods from another class (parent).
  • Can a child class override a method from its parent?
    Yes, a child class can override a parent method by defining a method with the same name.
  • How do you call a parent class constructor from a child class?
    By using parent::__construct() inside the childโ€™s constructor.
  • Can a child class access private properties of the parent class?
    No, private properties are not accessible in child classes; use protected instead.
  • Is multiple inheritance supported using extends in PHP?
    No, PHP supports only single inheritance per class.

Mid-Level Interview Questions

  • Explain the difference between public, protected, and private in the context of inheritance.
    Public members are accessible everywhere; protected members are accessible in the class and child classes; private members are accessible only within the parent class.
  • How do you access an overridden parent method from a child class?
    Using parent::methodName() inside the child class method.
  • What happens if a child class doesnโ€™t call the parent constructor?
    The parent constructor wonโ€™t run, potentially leaving inherited properties uninitialized.
  • Can you extend a final class in PHP?
    No, final classes cannot be extended.
  • How do you prevent a method from being overridden in child classes?
    Declare the method as final.

Senior-Level Interview Questions

  • How can careful use of inheritance improve code maintainability?
    By promoting code reuse, minimizing duplication, and creating clear hierarchies where child classes extend and specialize parent classes.
  • When would you choose composition over inheritance instead of using extends?
    When the relationship is โ€œhas-aโ€ rather than โ€œis-a,โ€ or to avoid tight coupling and deep inheritance hierarchies.
  • Explain how late static binding relates to inheritance in PHP.
    Late static binding allows static methods and properties to refer to the called class in context of inheritance, using the static:: keyword instead of self::.
  • How do traits complement class inheritance in PHP?
    Traits allow horizontal reuse of methods across classes without inheritance, helping to solve limitations of single inheritance.
  • Discuss potential drawbacks of deep inheritance hierarchies with extends.
    They can make code harder to understand, maintain, and debug due to tight coupling, hidden dependencies, and complexity.

FAQ

Can one child class extend multiple parent classes in PHP?
No, PHP supports only single inheritance per class. Use interfaces or traits for multiple inheritance behavior.
Does the child class inherit private members from the parent?
The child class inherits private members but cannot access them directly.
How do I override a parent method but still call its original functionality?
Inside the child method, you can call parent::methodName() to invoke the parentโ€™s method.
What visibility should I use to allow child classes to access properties?
Use protected visibility to allow access within child classes.
Is it mandatory to call the parent constructor in the child class?
No, but itโ€™s recommended to ensure parent initialization is done unless intentionally skipping it.

Conclusion

The extends keyword is fundamental in PHP for implementing class inheritance. By allowing child classes to inherit and extend the behavior of parent classes, it enables developers to write cleaner, reusable, and more organized object-oriented code. Understanding how to use extends correctly along with best practices and avoiding common pitfalls will equip you to design scalable PHP applications effectively.