Where to close a file handle opened at the beginning of a PHP script?

933 views Asked by At

I have a PHP file in which, on the top I create a file handle using fopen(). Then then file has a couple of classes, in the functions of which I write stuff to this text file. And ultimately, in the end, i.e. when I am done writing stuff to this file, I have to close this file handle using fclose().

The flow of control is such that, in the following pseudo-code, the function a_b() of class A is called LAST OF ALL in this PHP script. So, naturally, in the end of the body of a_b(), I decided to write fclose($fileHandle);.

BUT I got an ERROR: Notice: Undefined variable: fileHandle in C:\xampp\htdocs\Tests\Test.php on line 15

The question is why? Where should I write the statement fclose($fileHandle)? Should I write it at the very end of the file?

<?php 

$fileHandle = fopen($pathToFileHandle, "a");

class A {
  function a_a() {
    ...
    fwrite($fileHandle, "blahBlahBlah");
  }

  function a_b() {
    ...
    fwrite($fileHandle, "Whatever");
    ...
    fclose($fileHandle);
  }
}

class L {
  function l_a() {
    ...
    fwrite($fileHandle, "Some text");
    ...
  }
}

?>
2

There are 2 answers

0
symcbean On BEST ANSWER

Having inline code (i.e. code which does something rather code which defines something to be invoked later) mixed up in the same file, is considered a bad thing - not least because it gives rise to the kind of problem you describe here.

You don't need to explicitly close a file handle - PHP will do this automatically when the script exits.

If you want to do more than just close the file, an alternative to explicitly invoking the close in your thread of execution is to ask PHP to call a function when the script finishes executing (note that a callback can also be an object - i.e. with associated data).

As Renee points out, your issue arises from scope. However its also bad design to split the file operations across two different classes and the procedural side effect. Use a single class to define all the file operations (open, close, read, write). Then pass a reference to that class to other classes which will supply or require data to/from the file.

0
goto-bus-stop On

Undefined variable: fileHandle in C:\xampp\htdocs\Tests\Test.php on line 15

PHP functions cannot access global variables by default. So:

$value = 'hello world';
class A {
    public function b () {
        return $value;
    }
}

…does not work—$value is unavailable in the function.

Use the global keyword to make global variables available inside a function:

$value = 'hello world';
class A {
    public function b () {
        global $value;
        return $value;
    }
}

But, as commenters suggested, if possible it is better to keep the $fileHandle variable in the class that uses it and to close the handle as soon as possible.