Bird
0
0

What is the issue with the following PHP code snippet?

medium📝 Debug Q6 of 15
PHP - Inheritance and Polymorphism

What is the issue with the following PHP code snippet?

class Animal {}
class Cat extends Animal {}

function petAnimal(Animal $a) {
    echo "Petting animal";
}

petAnimal('cat');
APassing a string instead of an object causes a type error.
BThe function should type hint with Cat instead of Animal.
CThe class Cat must implement an interface to be accepted.
DThere is no error; the code runs fine.
Step-by-Step Solution
Solution:
  1. Step 1: Check parameter type hint

    The function expects an object of class Animal or subclass.
  2. Step 2: Analyze the argument

    The argument passed is a string 'cat', not an object.
  3. Step 3: Result

    PHP will throw a TypeError because the argument is not an object of Animal or subclass.
  4. Final Answer:

    Passing a string instead of an object causes a type error. -> Option A
  5. Quick Check:

    Type hint requires object, not string [OK]
Quick Trick: Type hint expects object, not string [OK]
Common Mistakes:
  • Assuming strings are accepted as objects
  • Thinking subclass hint is mandatory
  • Ignoring type errors on wrong argument types

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes