2009-12-27 58 views
1

我发现了一个logging script这样的:我是否必须明确关闭此文件?

/** 
* Logging class: 
* - contains lopen and lwrite methods 
* - lwrite will write message to the log file 
* - first call of the lwrite will open log file implicitly 
* - message is written with the following format: hh:mm:ss (script name) message 
*/ 
class Logging{ 
    // define log file 
    private $log_file = '/tmp/logfile.txt'; 
    // define file pointer 
    private $fp = null; 
    // write message to the log file 
    public function lwrite($message){ 
    // if file pointer doesn't exist, then open log file 
    if (!$this->fp) $this->lopen(); 
    // define script name 
    $script_name = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME); 
    // define current time 
    $time = date('H:i:s'); 
    // write current time, script name and message to the log file 
    fwrite($this->fp, "$time ($script_name) $message\n"); 
    } 
    // open log file 
    private function lopen(){ 
    // define log file path and name 
    $lfile = $this->log_file; 
    // define the current date (it will be appended to the log file name) 
    $today = date('Y-m-d'); 
    // open log file for writing only; place the file pointer at the end of the file 
    // if the file does not exist, attempt to create it 
    $this->fp = fopen($lfile . '_' . $today, 'a') or exit("Can't open $lfile!"); 
    } 
} 

我看不到任何文件,这里关闭代码。这很好吗?如果不是,那么在什么时候适合?或者脚本完全执行完毕后,PHP是否会关闭该文件?

回答

1

正如人们所说,PHP会自动关闭文件。但是,关闭文件是最佳实践。

  1. 在大多数语言中,您必须明确关闭文件,否则可能会导致数据丢失。所以这是一个很好的习惯,如果你曾经移植过你的应用程序,那么这很有帮助。

  2. 数据可能无法刷新到磁盘,直到关闭发生。如果你的脚本运行了一段时间(作为PHP脚本,它可能不会),那么你可能想要更明确地控制什么时候写入东西。对于我的“典型”日志记录应用程序,我打开并关闭每一行上的文件,以便在发生崩溃时保存日志。

  3. 最重要,也是被忽视的:它阻止下一个人不得不再次问这个问题!这是一个代码清晰度问题;如果你必须问是否正确,你应该考虑重写它,看起来是否正确。

0

关闭文件并不是绝对必要的,因为大多数C运行时会在进程结束时自动关闭文件。但是,在执行此操作时,某些C运行时可能不会刷新缓存中的数据,因此建议您关闭所有打开的文件以避免数据丢失。

+0

PHP自身关闭任何打开的文件,不需要涉及C运行时... – gnud 2009-12-27 17:59:28

0

实际上PHP将关闭它在脚本执行后处理的文件。

这是明确做到这一点的“最佳做法”,但在大多数情况下并不重要。我想,如果有一个不受欢迎的例外,你可能会留下一个'打开'的文件,而且它真的只需要一行就可以关闭 - 为什么不呢?

0

问题不在于关闭文件,而是在文件关闭之前刷新输出。如果一个文件完全关闭,那么就是这样 - 它已关闭。如果输出缓冲区中有任何剩余数据,则可能会丢失。

现在,PHP关闭文件时可能会“刷新并关闭”,我不知道。但是,这是关于不明确关闭文件的问题的第一件事情。

相关问题