Bird
0
0

What will be the output of the following PHP code?

medium📝 Predict Output Q13 of 15
PHP - Inheritance and Polymorphism
What will be the output of the following PHP code?
class ParentClass {
  public function __construct() {
    echo "Parent constructor called. ";
  }
}
class ChildClass extends ParentClass {
  public function __construct() {
    parent::__construct();
    echo "Child constructor called.";
  }
}
new ChildClass();
AChild constructor called.
BParent constructor called. Child constructor called.
CParent constructor called.
DNo output.
Step-by-Step Solution
Solution:
  1. Step 1: Trace constructor calls

    The child class constructor calls parent::__construct(); first, so the parent's constructor runs and prints "Parent constructor called. "
  2. Step 2: Continue child constructor execution

    After the parent's constructor, the child constructor prints "Child constructor called." immediately after.
  3. Final Answer:

    Parent constructor called. Child constructor called. -> Option B
  4. Quick Check:

    Child calls parent constructor then prints own message [OK]
Quick Trick: parent::__construct() runs parent's constructor first [OK]
Common Mistakes:
  • Ignoring parent::__construct() call in child constructor
  • Assuming only child constructor output appears
  • Thinking parent's constructor is not called explicitly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes