Bird
0
0

You want to ensure a file is always closed when your PHP object is destroyed. Which code snippet correctly uses a destructor to do this?

hard📝 Application Q15 of 15
PHP - Classes and Objects
You want to ensure a file is always closed when your PHP object is destroyed. Which code snippet correctly uses a destructor to do this?
class FileHandler {
  private $file;
  function __construct($filename) {
    $this->file = fopen($filename, 'w');
  }
  // What goes here?
}
Afunction __destruct() { open($this->file); }
Bfunction __destruct() { fclose($this->file); }
Cfunction __destruct() { fclose($filename); }
Dfunction __destruct() { $this->file = null; }
Step-by-Step Solution
Solution:
  1. Step 1: Understand resource cleanup in destructor

    The destructor should close the file resource held in $this->file using fclose().
  2. Step 2: Check each option for correctness

    function __destruct() { fclose($this->file); } correctly calls fclose($this->file);. function __destruct() { open($this->file); } tries to open instead of close. function __destruct() { fclose($filename); } uses undefined $filename. function __destruct() { $this->file = null; } just sets property to null without closing.
  3. Final Answer:

    function __destruct() { fclose($this->file); } -> Option B
  4. Quick Check:

    Destructor closes file resource properly [OK]
Quick Trick: Destructor should close resources like files with fclose() [OK]
Common Mistakes:
  • Calling wrong function like open() instead of fclose()
  • Using undefined variables inside destructor
  • Not actually closing the resource, just nullifying

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes