Bird
0
0

What is wrong with this PHP code?

medium📝 Debug Q6 of 15
PHP - Inheritance and Polymorphism
What is wrong with this PHP code?
class Bird {
  public function fly() {
    return "Flying";
  }
}
class Penguin extends Bird {
  public function fly() {
    echo "Penguins can't fly!";
  }
}
$penguin = new Penguin();
echo $penguin->fly();
APenguin cannot extend Bird because birds cannot be inherited.
BThe fly() method in Penguin uses echo instead of return, causing unexpected output.
CThe fly() method in Bird should be private to allow overriding.
DThe code is correct and will output 'Penguins can't fly!' without issues.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze method behavior

    Parent method fly() returns a string, child method echoes a string.
  2. Step 2: Check method call

    Calling echo on $penguin->fly() will echo the echoed string and then echo nothing (null), causing confusion.
  3. Final Answer:

    The fly() method in Penguin uses echo instead of return, causing unexpected output. -> Option B
  4. Quick Check:

    Child methods should match parent method return types. [OK]
Quick Trick: Child methods should return, not echo, if parent returns. [OK]
Common Mistakes:
  • Using echo inside methods expected to return values.
  • Thinking inheritance is invalid between related classes.
  • Making parent methods private to allow overriding.

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes