Bird
0
0

What will be the output of this PHP code?

medium📝 Predict Output Q4 of 15
PHP - Inheritance and Polymorphism
What will be the output of this PHP code?
class Animal {
  public function sound() {
    return "Animal sound";
  }
}
class Dog extends Animal {
  public function sound() {
    return parent::sound() . " and Bark";
  }
}
$pet = new Dog();
echo $pet->sound();
AError: Cannot access parent method
BBark
CAnimal sound
DAnimal sound and Bark
Step-by-Step Solution
Solution:
  1. Step 1: Analyze parent method call

    The Dog class overrides sound() but calls parent::sound() to get the base message.
  2. Step 2: Concatenate strings

    The returned string from parent is concatenated with " and Bark".
  3. Final Answer:

    Animal sound and Bark -> Option D
  4. Quick Check:

    parent:: calls base method, concatenated result printed [OK]
Quick Trick: parent:: calls base method, concatenated result printed [OK]
Common Mistakes:
  • Expecting only 'Bark' without parent call
  • Assuming error due to parent:: usage
  • Ignoring string concatenation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes