Bird
0
0

Identify the problem in this PHP code snippet:

medium📝 Debug Q7 of 15
PHP - Inheritance and Polymorphism

Identify the problem in this PHP code snippet:

class User {}
class Admin extends User {}

function login(Admin $a) {
    echo "Admin logged in";
}

$user = new User();
login($user);
APassing a User object to a function expecting Admin causes a type error.
BThe function should accept User instead of Admin to avoid errors.
CThere is no problem; User is a parent of Admin.
DThe class Admin must extend another class to work.
Step-by-Step Solution
Solution:
  1. Step 1: Understand type hinting

    The function expects an Admin object.
  2. Step 2: Analyze argument

    The argument is a User object, which is a parent class, not a subclass.
  3. Step 3: Result

    PHP does not allow passing a parent class object where a subclass is expected, causing a TypeError.
  4. Final Answer:

    Passing a User object to a function expecting Admin causes a type error. -> Option A
  5. Quick Check:

    Subclass type hint requires subclass object [OK]
Quick Trick: Subclass hint requires subclass object [OK]
Common Mistakes:
  • Passing parent class object to subclass type hint
  • Assuming parent objects are accepted by subclass hints
  • Ignoring PHP type errors on incompatible objects

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes