0
0
PHPprogramming~5 mins

Type hinting with parent classes in PHP

Choose your learning style9 modes available
Introduction

Type hinting with parent classes helps your program know what kind of objects to expect. It makes your code safer and easier to understand.

When you want a function to accept any object that is a child of a specific parent class.
When you want to make sure an object passed to a method has certain properties or methods from the parent class.
When you want to write flexible code that works with many related classes.
When you want to avoid errors by checking object types before using them.
Syntax
PHP
function exampleFunction(ParentClass $obj) {
    // code using $obj
}

The type hint uses the parent class name before the variable.

This means any object that is an instance of the parent class or its child classes is allowed.

Examples
This example shows a function that accepts any Animal or its child classes like Dog.
PHP
<?php
class Animal {}
class Dog extends Animal {}

function feedAnimal(Animal $animal) {
    echo "Feeding an animal.\n";
}

$dog = new Dog();
feedAnimal($dog);
The function startEngine accepts any Vehicle or subclass like Car.
PHP
<?php
class Vehicle {}
class Car extends Vehicle {}

function startEngine(Vehicle $vehicle) {
    echo "Starting engine.\n";
}

$car = new Car();
startEngine($car);
Sample Program

This program shows a function that accepts any Fruit or its child classes. It calls the eat method, which behaves differently for Apple.

PHP
<?php
class Fruit {
    public function eat() {
        echo "Eating fruit.\n";
    }
}

class Apple extends Fruit {
    public function eat() {
        echo "Eating apple.\n";
    }
}

function enjoyFruit(Fruit $fruit) {
    $fruit->eat();
}

$apple = new Apple();
enjoyFruit($apple);
OutputSuccess
Important Notes

Type hinting with parent classes allows flexibility while keeping type safety.

If you pass an object not related to the parent class, PHP will give an error.

This helps catch mistakes early and makes your code easier to read.

Summary

Type hinting with parent classes lets functions accept any child class objects.

It improves code safety and flexibility.

Use it to ensure objects have expected methods or properties.