Consider the following PHP code. What will it output when run?
<?php class Test { public function __construct() { echo "Constructed\n"; } public function __destruct() { echo "Destructed\n"; } } $obj = new Test(); echo "End of script\n"; ?>
Remember that the destructor runs when the object is destroyed, usually at the end of the script.
The constructor runs first, printing "Constructed". Then the script prints "End of script". Finally, when the script ends and the object is destroyed, the destructor prints "Destructed".
What will this PHP code output?
<?php class Sample { public function __destruct() { echo "Bye!\n"; } } $obj = new Sample(); unset($obj); echo "After unset\n"; ?>
Think about when the destructor is called if you unset the object manually.
When you unset the object, the destructor runs immediately, printing "Bye!". Then the script prints "After unset".
Look at this PHP code. The destructor message is never printed. Why?
<?php class Demo { public function __destruct() { echo "Destroying\n"; } } function create() { $obj = new Demo(); } create(); echo "Done\n"; ?>
Think about when local variables inside functions are destroyed.
The object $obj is destroyed as soon as the function create() finishes, so the destructor runs before the "Done" message is printed.
Choose the correct way to declare a destructor method in a PHP class.
Destructor method name must be exactly __destruct with parentheses.
In PHP, the destructor method must be named __destruct with parentheses and a function body.
Consider this PHP code. What will be the exact output?
<?php class A { public function __destruct() { echo "A destroyed\n"; } } class B { public function __destruct() { echo "B destroyed\n"; } } $a = new A(); $b = new B(); unset($a); echo "Middle\n"; ?>
Think about when each object is destroyed and when the script ends.
When unset($a) runs, A's destructor prints "A destroyed". Then "Middle" is printed. At script end, B's destructor runs, printing "B destroyed".