Core PHP

A Class Destructor

A destructor provides to free or uninitialize the resources that were allocated or initialized in the constructor. The basic relationship between the constructor and the destructor is they begin and end an object's existence.

The syntax of the destructor is similar to the constructor. Both look like functions with names that begin with double underline characters. The constructor is called by the user via the "new' command, but the destructor is typically called when the program chooses to deallocate the object.

This program uses the constructor to open a file for reading and the destructor to close the file when the reader is deallocated. There echo statements in each to make the calls visible. In between, we read out the text from the file "Isaiah53.txt" that was specified at the instantiation.

CFileReader.php

<?php
  class CFileReader {
    var $mqFileHandle;

    public function __construct($sFileName) {
      $this->mqFileHandle = fopen($sFileName, "r") or die("Unable to open file!");
      echo "<b>The file has been opened.</b><br /><br />";
    }

    public function __destruct() {
      fclose($this->mqFileHandle);
      echo "<br /><b>The file has been closed.</b><br />";
    }
  }

  $qFileReader = new CFileReader("Isaiah53.txt");
  while(!feof($qFileReader->mqFileHandle)) {
    echo fgets($qFileReader->mqFileHandle)."<br />";
  }
?>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.