PHP Inheritance

PHP

PHP Inheritance - extends Keyword

SEO Description: Learn PHP inheritance - parent and child classes

Introduction

Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a class to inherit properties and methods from another class. In PHP, inheritance enables the creation of hierarchical class relationships where a child class inherits the features of a parent class. This promotes code reusability and makes your codebase easier to maintain.

In this tutorial, you will learn how to use the extends keyword in PHP to implement inheritance, explore method overriding, and understand best practices to use inheritance effectively in your applications.

Prerequisites

  • Basic understanding of PHP programming
  • Familiarity with PHP classes and objects
  • Knowledge of basic OOP concepts such as encapsulation and methods
  • PHP environment set up (PHP 7.0 or higher recommended)

Setup

To follow along with this tutorial, ensure you have a PHP development environment ready. You can run PHP scripts locally using:

  • XAMPP, WAMP (Windows)
  • MAMP (Mac)
  • Native PHP installed on Linux
  • Or any online PHP sandbox (e.g., https://3v4l.org, https://phpfiddle.org/)

Save your PHP scripts with a .php extension and run them via your web server or command line interface.

Understanding PHP Inheritance and the extends Keyword

Inheritance allows a class to inherit properties and methods from another class using the extends keyword.

Syntax:

class ChildClass extends ParentClass {
    // Additional properties or methods here
}
  

The child class inherits all public and protected methods and properties from the parent class, except private members.

Example 1: Basic Inheritance

<?php
// Parent class
class Animal {
    public $name;

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

    public function speak() {
        echo "Some generic animal sound." . PHP_EOL;
    }
}

// Child class inherits from Animal
class Dog extends Animal {
    public function speak() {
        echo $this->name . " says: Woof!" . PHP_EOL;
    }
}

$dog = new Dog("Buddy");
$dog->speak(); // Output: Buddy says: Woof!
?>
  

In this example, Dog inherits properties and methods from Animal, and overrides the speak() method.

Method Overriding

Method overriding is when a child class redefines a method that exists in the parent class to provide a specialized behavior.

Example 2: Calling Parent Methods with parent::

<?php
class Bird extends Animal {
    public function speak() {
        // Call parent method
        parent::speak();

        // Additional behavior
        echo $this->name . " says: Tweet!" . PHP_EOL;
    }
}

$bird = new Bird("Tweety");
$bird->speak();
// Output: 
// Some generic animal sound.
// Tweety says: Tweet!
?>
  

You can extend the parent method by calling parent::methodName() inside the childโ€™s method.

Best Practices for Using PHP Inheritance

  • Use inheritance for IS-A relationships: Child classes should be a more specific type of the parent class.
  • Favor composition over inheritance: Use inheritance only when necessary to avoid tight coupling.
  • Override methods carefully: Always consider if overriding is needed or if you can add new methods.
  • Use protected properties/methods: Enables child classes to access while keeping them hidden from outside.
  • Document overridden methods: Clarify behavior changes for maintainability.

Common Mistakes in PHP Inheritance

  • Trying to override private methods: Private members are not inherited, so overriding them wonโ€™t work.
  • Not calling parent constructor: If the parent constructor does important initialization, not calling it can cause bugs.
  • Excessive inheritance depth: Deep inheritance chains can be difficult to manage.
  • Misusing inheritance for unrelated classes: Avoid inheritance when classes donโ€™t share is-a relationships.
  • Ignoring method visibility: Public and protected can be accessed; private cannot be overridden.

Interview Questions

Junior-Level Questions

  • Q1: What does the extends keyword do in PHP?
    A1: It allows a child class to inherit properties and methods from a parent class.
  • Q2: Can a child class access private properties of its parent?
    A2: No, private properties are not accessible or inherited by the child class.
  • Q3: How do you override a method in a child class?
    A3: By defining a method with the same name in the child class.
  • Q4: What happens if a child class does not override a parent method?
    A4: The child class inherits the parent's method and uses it as-is.
  • Q5: How would you create a child class named Car that inherits from Vehicle?
    A5: class Car extends Vehicle {}

Mid-Level Questions

  • Q1: What is method overriding and how is it implemented in PHP inheritance?
    A1: Method overriding occurs when a child class provides its own implementation of a method defined in the parent, simply by redeclaring it.
  • Q2: How can you call a parentโ€™s method inside an overridden method?
    A2: Using parent::methodName() inside the childโ€™s method.
  • Q3: Explain the difference between public, protected, and private members in inheritance.
    A3: Public members are accessible everywhere, protected members accessible in parent and child classes, private members only accessible within the declaring class.
  • Q4: Why is it important to call the parent constructor in a child class?
    A4: Because the parent constructor might initialize important properties or resources needed by the child.
  • Q5: Can PHP classes extend more than one class?
    A5: No, PHP does not support multiple inheritance through classes; however, traits can be used to include multiple sets of methods.

Senior-Level Questions

  • Q1: How does late static binding affect method calls in inherited PHP classes?
    A1: Late static binding allows static calls to refer to the called class, not necessarily the class where the method is defined, which is useful in inheritance hierarchies.
  • Q2: How would you prevent a class from being extended in PHP?
    A2: Declaring the class as final prevents other classes from extending it.
  • Q3: Can you override static methods in PHP inheritance and how?
    A3: Yes, defining a static method with the same name in a child class overrides the parentโ€™s static method.
  • Q4: What are the implications of deep inheritance hierarchies on maintainability?
    A4: Deep hierarchies complicate understanding, debugging, and flexibility; favor flatter designs or composition when possible.
  • Q5: Describe a scenario where calling parent:: inside a constructor is necessary.
    A5: When the parent constructor initializes critical properties or sets up resources required for the child class functionality.

FAQ

  • Q: Can a PHP class inherit from multiple classes?

    A: No, PHP supports single inheritance only, but you can use traits for code reuse from multiple sources.

  • Q: Are private properties inherited in PHP?

    A: Private properties exist only in the class that declares them; child classes cannot access or override them.

  • Q: What is the difference between method overriding and method overloading?

    A: PHP supports method overriding (redefining a parent method in a child class) but does not natively support method overloading (multiple methods with the same name but different parameters).

  • Q: How do you ensure a method canโ€™t be overridden?

    A: Declare the method as final in the parent class to prevent overriding.

  • Q: Can constructors be overridden in PHP inheritance?

    A: Yes, child classes can override constructors, but itโ€™s recommended to call parent::__construct() from the child constructor to initialize the parent properly.

Conclusion

PHP inheritance using the extends keyword is a core OOP feature that allows child classes to reuse and customize the behavior of parent classes, promoting code reuse and extensibility. Method overriding provides flexibility to tailor inherited methods, while best practices and awareness of common pitfalls ensure you use inheritance effectively.

By mastering inheritance, you can build better-structured PHP applications that are easier to maintain and extend. Keep practicing by creating parent-child class relationships, experimenting with method overriding, and leveraging parent:: calls wisely.