I’m writing a logging tool which writes messages to a file, and I’m not sure of the best way to deal with the file pointer. I’m tossing up between these two methods:
// Open, Write, Close; Open, Write, Close...
function write($message) {
$fh = fopen('file.log', 'a');
fwrite($fh, $message . "\n");
fclose($fh);
}
// OR -----
// Open, Write, Write, Write..., Close
function __construct() {
$this->fh = fopen('file.log', 'a');
}
function __destruct() {
fclose($this->fh);
}
function write($message) {
fwrite($fh, $message . "\n");
}
I imagine that this class will be loaded and constructed on every page, but not necessarily used, though it most likely will be.
Are there are performance, security or miscellaneous pitfalls of either method, and which would you recommend?
I can’t give you a number, but opening a file just to close and reopen it repeatedly is going to cost you something. And I’m talking at the OS level, not just PHP. Calling into the kernel for
open()(orCreateFile()if you speak Windows), matching path strings to entities from your filesystem, reading directory structure from disk, then another syscall to close the handle… Especially if you have a large number of this I would avoid doing all this too much. Or get some measurements to see if it’s OK.If you’re worried about incurring cost for something that will never be used, have you considered a mix of these two approaches? That is, doing an open on write if the file isn’t already open, otherwise reusing the old handle…