Bird
0
0

What will be the output of this PHP code?

medium📝 Predict Output Q5 of 15
PHP - Inheritance and Polymorphism
What will be the output of this PHP code?
class ParentClass {
  public function __construct() {
    echo "Parent\n";
  }
}
class ChildClass extends ParentClass {
  public function __construct() {
    parent::__construct();
    echo "Child\n";
  }
}
new ChildClass();
AChild\nParent
BParent
CParent\nChild
DChild
Step-by-Step Solution
Solution:
  1. Step 1: Check constructor calls in ChildClass

    ChildClass constructor calls parent::__construct() first, then echoes "Child".
  2. Step 2: Determine output order

    Output will be "Parent" followed by "Child" each on new lines.
  3. Final Answer:

    Parent\nChild -> Option C
  4. Quick Check:

    Explicit parent call runs first, then child code [OK]
Quick Trick: Call parent::__construct() first to run parent constructor [OK]
Common Mistakes:
  • Reversing output order
  • Forgetting parent::__construct() call
  • Expecting only child output

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes