Bird
0
0

What will be the output of the following PHP code?

medium📝 Predict Output Q13 of 15
PHP - Classes and Objects
What will be the output of the following PHP code?
class Test {
  function __construct() {
    echo "Constructed\n";
  }
  function __destruct() {
    echo "Destructed\n";
  }
}
$obj = new Test();
echo "Hello\n";
unset($obj);
AConstructed\nDestructed\nHello\n
BHello\nConstructed\nDestructed\n
CDestructed\nConstructed\nHello\n
DConstructed\nHello\nDestructed\n
Step-by-Step Solution
Solution:
  1. Step 1: Trace object creation and constructor call

    When $obj = new Test(); runs, __construct() prints "Constructed\n".
  2. Step 2: Print "Hello" and then unset object

    Next, "Hello\n" is printed. Then unset($obj); destroys the object, triggering __destruct() which prints "Destructed\n".
  3. Final Answer:

    Constructed\nHello\nDestructed\n -> Option D
  4. Quick Check:

    Constructor then echo then destructor [OK]
Quick Trick: Destructor runs when object is unset or script ends [OK]
Common Mistakes:
  • Assuming destructor runs before echo
  • Confusing order of constructor and destructor
  • Missing that unset triggers destructor immediately

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes