fopen - Where to close a file handle opened at the beginning of a PHP script? -
i have php file in which, on top create file handle using fopen()
. then file has couple of classes, in functions of write stuff text file. , ultimately, in end, i.e. when done writing stuff file, have close file handle using fclose()
.
the flow of control such that, in following pseudo-code, function a_b()
of class a
called last of in php script. so, naturally, in end of body of a_b()
, decided write fclose($filehandle);
.
but got error: notice: undefined variable: filehandle in c:\xampp\htdocs\tests\test.php on line 15
the question why? should write statement fclose($filehandle)
? should write @ end of file?
<?php $filehandle = fopen($pathtofilehandle, "a"); class { function a_a() { ... fwrite($filehandle, "blahblahblah"); } function a_b() { ... fwrite($filehandle, "whatever"); ... fclose($filehandle); } } class l { function l_a() { ... fwrite($filehandle, "some text"); ... } } ?>
having inline code (i.e. code rather code defines invoked later) mixed in same file, is considered bad thing - not least because gives rise kind of problem describe here.
you don't need explicitly close file handle - php automatically when script exits.
if want more close file, alternative explicitly invoking close in thread of execution ask php call function when script finishes executing (note callback can object - i.e. associated data).
as renee points out, issue arises scope. bad design split file operations across 2 different classes , procedural side effect. use single class define file operations (open, close, read, write). pass reference class other classes supply or require data to/from file.
Comments
Post a Comment