PHP Inheritance


Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one class to inherit the properties and methods of another class. This promotes code reuse, logical hierarchy, and better organization. Understanding inheritance in PHP is key to writing modular and maintainable code. In this article, we will explore common interview questions and answers related to PHP inheritance.


What is inheritance in PHP?

Answer:
Inheritance in PHP is a mechanism that allows a class (child or subclass) to inherit properties and methods from another class (parent or superclass). The child class can access the parent class’s properties and methods, and it can also add new properties or methods or override existing ones.

Example:

class Vehicle {
   public $brand;
   public function startEngine() {
      echo "Engine started.";
   }
}
class Car extends Vehicle {
   public $model;
}
$car = new Car();
$car->startEngine(); // Inherits startEngine() method from Vehicle

What are the benefits of inheritance in PHP?

Answer:

  • Code Reusability: You can reuse code from the parent class in multiple child classes, reducing duplication.
  • Logical Structure: Inheritance allows for logical class hierarchies, making code more organized.
  • Extensibility: Child classes can extend or modify the behavior of parent classes by adding or overriding methods.
  • Maintainability: Changes in a parent class automatically affect child classes, making maintenance easier.

How do you create a child class that inherits from a parent class in PHP?

Answer:
In PHP, you create a child class using the extends keyword. This allows the child class to inherit all properties and methods from the parent class.

Example:

class ParentClass {
   public function sayHello() {
      echo "Hello from Parent!";
   }
}
class ChildClass extends ParentClass {
}
$child = new ChildClass();
$child->sayHello(); // Outputs: Hello from Parent!

Can a child class override a method from a parent class?

Answer:
Yes, a child class can override a method inherited from a parent class by defining the method with the same name. When the overridden method is called on an object of the child class, the child class’s version is executed.

Example:

class ParentClass {
   public function sayHello() {
      echo "Hello from Parent!";
   }
}
class ChildClass extends ParentClass {
   public function sayHello() {
      echo "Hello from Child!";
   }
}
$child = new ChildClass();
$child->sayHello(); // Outputs: Hello from Child!

How can you call the parent class's method in the child class?

Answer:
You can call the parent class’s method in the child class using the parent:: keyword.

Example:

class ParentClass {
   public function sayHello() {
      echo "Hello from Parent!";
   }
}
class ChildClass extends ParentClass {
   public function sayHello() {
      parent::sayHello(); // Call the parent method
      echo " Hello from Child!";
   }
}
$child = new ChildClass();
$child->sayHello(); // Outputs: Hello from Parent! Hello from Child!

Can a child class override the constructor of a parent class?

Answer:
Yes, a child class can override the constructor of a parent class by defining its own __construct() method. The parent class constructor will not be called unless explicitly invoked using parent::__construct().

Example:

class ParentClass {
   public function __construct() {
      echo "Parent constructor called.<br>";
   }
}
class ChildClass extends ParentClass {
   public function __construct() {
      parent::__construct(); // Call parent constructor
      echo "Child constructor called.";
   }
}
$child = new ChildClass();

Output:

Parent constructor called.
Child constructor called.

What is multiple inheritance, and does PHP support it?

Answer:
Multiple inheritance refers to a class inheriting properties and methods from more than one parent class. PHP does not support multiple inheritance directly, but it does support traits, which allow code to be reused across multiple classes.

Example using traits:

trait Driveable {
   public function drive() {
      echo "Driving the car.";
   }
}
trait Flyable {
   public function fly() {
      echo "Flying the plane.";
   }
}
class Vehicle {
   use Driveable, Flyable; // Using multiple traits
}
$vehicle = new Vehicle();
$vehicle->drive(); // Outputs: Driving the car.
$vehicle->fly();   // Outputs: Flying the plane.

What is the difference between overriding and overloading methods in PHP?

Answer:

  • Overriding: Occurs when a child class provides its own implementation of a method that exists in the parent class. The child class method overrides the parent class method.
  • Overloading: PHP does not support method overloading directly (i.e., defining multiple methods with the same name but different parameters). However, PHP can achieve overloading-like behavior by using func_num_args() or __call() magic methods.

What is the final keyword in PHP, and how does it relate to inheritance?

Answer:
The final keyword in PHP is used to prevent a class from being extended or a method from being overridden by child classes.

  • Final class: A class declared as final cannot be extended.
  • Final method: A method declared as final cannot be overridden in any subclass.

Example:

final class Vehicle {
   // This class cannot be extended
}
class Car {
   final public function startEngine() {
      echo "Engine started.";
   }
}
class SportsCar extends Car {
   // Cannot override startEngine() because it is final
}

What is hierarchical inheritance in PHP?

Answer:
Hierarchical inheritance occurs when multiple child classes inherit from the same parent class. In this type of inheritance, different child classes can share the same properties and methods defined in the parent class but can implement their own unique features.

Example:

class Animal {
   public function makeSound() {
      echo "Animal sound!";
   }
}
class Dog extends Animal {
   public function bark() {
      echo "Bark!";
   }
}
class Cat extends Animal {
   public function meow() {
      echo "Meow!";
   }
}
$dog = new Dog();
$dog->makeSound(); // Inherited method
$dog->bark();      // Dog's own method
$cat = new Cat();
$cat->makeSound(); // Inherited method
$cat->meow();      // Cat's own method

Can a child class inherit private properties or methods from a parent class?

Answer:
No, private properties and methods cannot be inherited by a child class. They are accessible only within the class where they are defined. However, protected and public properties and methods are inherited.

Example:

class ParentClass {
   private $privateProperty = "Private";
   protected $protectedProperty = "Protected";
   public $publicProperty = "Public";
   private function privateMethod() {
      echo "Private Method";
   }
   protected function protectedMethod() {
      echo "Protected Method";
   }
   public function publicMethod() {
      echo "Public Method";
   }
}
class ChildClass extends ParentClass {
   public function displayProperties() {
      // echo $this->privateProperty; // Error: Cannot access private property
      echo $this->protectedProperty; // Works: Inherited protected property
      echo $this->publicProperty;    // Works: Inherited public property
   }
   public function callMethods() {
      // $this->privateMethod(); // Error: Cannot call private method
      $this->protectedMethod(); // Works: Inherited protected method
      $this->publicMethod();    // Works: Inherited public method
   }
}
$child = new ChildClass();
$child->displayProperties();
$child->callMethods();

What is a parent constructor, and how is it used in inheritance?

Answer:
A parent constructor is a constructor method defined in the parent class. When a child class extends the parent class, it can call the parent constructor using parent::__construct(). This is useful when the parent class constructor initializes certain properties that the child class needs to inherit.

Example:

class ParentClass {
   public $name;
   public function __construct($name) {
      $this->name = $name;
      echo "Parent constructor: $name<br>";
   }
}
class ChildClass extends ParentClass {
   public function __construct($name) {
      parent::__construct($name); // Call the parent constructor
      echo "Child constructor: $name<br>";
   }
}
$child = new ChildClass("John");

Output:

Parent constructor: John
Child constructor: John

What is the purpose of the instanceof operator in PHP?

Answer:
The instanceof operator checks if an object is an instance of a specific class or if the object’s class is a subclass of the specified class. It returns true if the object belongs to that class or a class that inherits from it.

Example:

class ParentClass {}
class ChildClass extends ParentClass {}
$child = new ChildClass();
if ($child instanceof ParentClass) {
   echo "ChildClass is an instance of ParentClass.";
}

What happens if a child class does not call the parent constructor?

Answer:
If the child class does not explicitly call the parent constructor using parent::__construct(), the parent constructor is not executed automatically. This could lead to incomplete initialization of inherited properties.

Example:

class ParentClass {
   public $name;
   public function __construct($name) {
      $this->name = $name;
   }
}
class ChildClass extends ParentClass {
   // Does not call parent::__construct(), so $name will not be initialized
}
$child = new ChildClass("John");
echo $child->name; // Outputs nothing since the parent constructor wasn't called

Can a class extend multiple classes in PHP?

Answer:
No, PHP does not support multiple inheritance directly, meaning a class cannot extend more than one class. However, PHP provides traits to reuse code across multiple classes and achieve behavior similar to multiple inheritance.

Ads