Consider the following PHP class with constructor and destructor methods. What will be printed when the script runs?
<?php class Test { public function __construct() { echo "Start\n"; } public function __destruct() { echo "End\n"; } } $obj = new Test(); echo "Middle\n"; ?>
Remember that the constructor runs when the object is created, and the destructor runs when the script ends or the object is destroyed.
The constructor prints "Start" immediately when the object is created. Then "Middle" is printed. Finally, when the script ends, the destructor prints "End".
Look at this PHP code. What will be the output?
<?php class Counter { public $count = 0; public function __construct() { $this->count = 1; echo "Construct: {$this->count}\n"; } public function __destruct() { $this->count++; echo "Destruct: {$this->count}\n"; } } $obj = new Counter(); echo "Count: {$obj->count}\n"; ?>
The destructor runs after the last output, so the property change is visible only inside the destructor.
The constructor sets count to 1 and prints it. Then the script prints count (1). Finally, the destructor increments count to 2 and prints it.
Examine this PHP class. What error will occur when running this code?
<?php class Sample { public function __construct() { echo "Hello\n"; } } $obj = new Sample(); ?>
Check the syntax carefully, especially punctuation after statements.
The echo statement is missing a semicolon at the end, causing a syntax error at the closing brace.
Choose the correct statement about when the __destruct method is called in PHP.
Think about object lifecycle and script execution.
The destructor runs when the object is no longer used or when the script finishes, not immediately after construction or only on unset.
Analyze this PHP code. How many times will the __destruct method be called before the script ends?
<?php class Logger { public function __construct() { echo "Logger started\n"; } public function __destruct() { echo "Logger ended\n"; } } function createLogger() { $log = new Logger(); } createLogger(); $log = new Logger(); ?>
Consider when objects go out of scope and when destructors run.
The first Logger object inside createLogger() is destroyed when the function ends, calling __destruct once. The second Logger object is destroyed at script end, calling __destruct again. Total 2 times.