Bird
0
0

What will happen when the following PHP code runs?

medium📝 Predict Output Q5 of 15
PHP - Inheritance and Polymorphism
What will happen when the following PHP code runs?
class Vehicle {}
class Bike {}

function ride(Vehicle $v) {
    echo "Riding vehicle";
}

$bike = new Bike();
ride($bike);
ARiding vehicle
BFatal error: Argument must be instance of Vehicle
CNo output
DWarning but continues execution
Step-by-Step Solution
Solution:
  1. Step 1: Analyze type hint and argument

    The function ride requires a Vehicle object, but $bike is an instance of Bike, unrelated to Vehicle.
  2. Step 2: Understand PHP behavior on type mismatch

    Passing an object not matching the type hint causes a fatal error.
  3. Final Answer:

    Fatal error: Argument must be instance of Vehicle -> Option B
  4. Quick Check:

    Type hint mismatch causes fatal error [OK]
Quick Trick: Type hint mismatch causes fatal error, no warnings [OK]
Common Mistakes:
  • Expecting warning instead of fatal error
  • Assuming unrelated classes are accepted
  • Thinking code runs silently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes