0
0
PHPprogramming~10 mins

Type hinting with parent classes in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to type hint the parameter as the parent class.

PHP
<?php
class Animal {}
function feed([1] $animal) {
    echo "Feeding animal";
}
?>
Drag options to blanks, or click blank then click option'
ABird
BDog
CCat
DAnimal
Attempts:
3 left
💡 Hint
Common Mistakes
Using a child class name instead of the parent class for type hinting.
2fill in blank
medium

Complete the method signature to accept any subclass of Vehicle using type hinting.

PHP
<?php
class Vehicle {}
class Car extends Vehicle {}
function startEngine([1] $vehicle) {
    echo "Engine started";
}
?>
Drag options to blanks, or click blank then click option'
ACar
BVehicle
CEngine
DMotor
Attempts:
3 left
💡 Hint
Common Mistakes
Type hinting with a subclass instead of the parent class.
3fill in blank
hard

Fix the error by correctly type hinting the parameter to accept any subclass of Fruit.

PHP
<?php
class Fruit {}
class Apple extends Fruit {}
function eat([1] $fruit) {
    echo "Eating fruit";
}
?>
Drag options to blanks, or click blank then click option'
AFruit
BApple
CFood
DVegetable
Attempts:
3 left
💡 Hint
Common Mistakes
Using a subclass name which restricts accepted types.
4fill in blank
hard

Fill both blanks to create a function that accepts any subclass of Device and calls its method.

PHP
<?php
class Device {
    public function powerOn() {
        echo "Device powered on";
    }
}
class Phone extends Device {}
function activate([1] $device) {
    $device->[2]();
}
?>
Drag options to blanks, or click blank then click option'
ADevice
BpowerOn
Cstart
DPhone
Attempts:
3 left
💡 Hint
Common Mistakes
Type hinting with a subclass or calling a method that does not exist.
5fill in blank
hard

Fill all three blanks to define a function that accepts any subclass of Employee, checks the role, and prints a message.

PHP
<?php
class Employee {
    public function getRole() {
        return "Employee";
    }
}
class Manager extends Employee {
    public function getRole() {
        return "Manager";
    }
}
function printRole([1] $emp) {
    if ($emp->getRole() === [2]) {
        echo [3];
    }
}
?>
Drag options to blanks, or click blank then click option'
AEmployee
B"Manager"
C"Manager role detected"
DManager
Attempts:
3 left
💡 Hint
Common Mistakes
Using subclass name as type hint or incorrect string literals.