Bird
0
0

What will be the output of this PHP code?

medium📝 Predict Output Q4 of 15
PHP - Classes and Objects
What will be the output of this PHP code?
class Sample {
  function __destruct() {
    echo "Goodbye!";
  }
}
$obj = new Sample();
echo "Hello!";
unset($obj);
AGoodbye!Hello!
BHello!Goodbye!
CHello!
DGoodbye!
Step-by-Step Solution
Solution:
  1. Step 1: Analyze code execution order

    First, the object is created but constructor is not defined, so no output. Then "Hello!" is printed.
  2. Step 2: Understand unset effect

    Calling unset($obj) destroys the object, triggering the destructor which prints "Goodbye!" immediately after "Hello!".
  3. Final Answer:

    Hello!Goodbye! -> Option B
  4. Quick Check:

    Destructor runs on unset = B [OK]
Quick Trick: Destructor runs when object is unset or script ends [OK]
Common Mistakes:
  • Expecting destructor to run before echo
  • Ignoring unset triggers destructor
  • Thinking destructor runs only at script end

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes