Bird
0
0

What will be the output of the following PHP code?

medium📝 Predict Output Q4 of 15
PHP - Inheritance and Polymorphism
What will be the output of the following PHP code?
class Animal {}
class Dog extends Animal {}

function greet(Animal $a) {
    echo "Hello from Animal!";
}

$dog = new Dog();
greet($dog);
AFatal error: Argument must be Animal
BNo output
CHello from Dog!
DHello from Animal!
Step-by-Step Solution
Solution:
  1. Step 1: Understand type hinting with parent classes

    The function greet expects an Animal object or subclass instance.
  2. Step 2: Check the argument passed

    $dog is an instance of Dog, which extends Animal, so it is accepted.
  3. Final Answer:

    Hello from Animal! -> Option D
  4. Quick Check:

    Parent class type hint accepts subclass instance = output printed [OK]
Quick Trick: Parent class hint accepts subclass objects without error [OK]
Common Mistakes:
  • Expecting error for subclass instance
  • Thinking output changes based on subclass
  • Ignoring inheritance in type hinting

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes