Bird
0
0

What will be the output of the following PHP code?

medium📝 Predict Output Q4 of 15
PHP - Inheritance and Polymorphism
What will be the output of the following PHP code?
class A {
  public function __construct() {
    echo "A constructor\n";
  }
}
class B extends A {
  public function __construct() {
    echo "B constructor\n";
  }
}
new B();
AA constructor\nB constructor
BB constructor
CA constructor
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Analyze constructors in classes A and B

    Class B defines its own constructor and does not call parent::__construct(), so only B's constructor runs.
  2. Step 2: Determine output when new B() is created

    Only "B constructor" is printed because parent constructor is not called automatically.
  3. Final Answer:

    B constructor -> Option B
  4. Quick Check:

    Child constructor overrides parent unless parent::__construct() called [OK]
Quick Trick: Child constructor overrides parent unless called explicitly [OK]
Common Mistakes:
  • Assuming both constructors run automatically
  • Expecting parent constructor output without call
  • Confusing output order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes