duanbu1421 2010-12-22 14:08
浏览 60

PHP中的错误处理。 怎么做?

I'm a beginner in PHP OOP and I'm with some doubts about the correct way of handling errors in PHP.

Look at this function for example:

public function deleteFileFromDisk($fileNameToBeDeleted) {

    $handle = unlink($fileNameToBeDeleted);

    if (!$handle) {
        $result = "(this->deleteFileFromDisk) - Error, " . $fileNameToBeDeleted . " not deleted.";
    } else {
        $result = "(this->deleteFileFromDisk) - Success, " . $fileNameToBeDeleted . " deleted.";
    }
    return $result;
}

Is this the correct way of doing it, or I can do better than this?

Let me add some details of what I'm achieving...

I'm running class methods, and I need to control errors in the process. If any call to the object throw an error I need to catch it and send an e-mail.

Here are the object interactions:

$testar_classe = new geoIpImportCSV('geolitecity', 'http://geolite.maxmind.com/download/geoip/database/GeoLiteCity_CSV/');
$testar_classe->downloadAndSaveFile('./', $testar_classe->obtainDownloadFileName());
$testar_classe->uncompressZipFile($testar_classe->obtainDownloadFileName(), '.');
$testar_classe->deleteLine(1, 'GeoLiteCity-Location.csv');               
$testar_classe->deleteLine(1, 'GeoLiteCity-Blocks.csv');
$testar_classe->deleteDataFromTable('tabela1');
$testar_classe->deleteDataFromTable('tabela2');
$testar_classe->insertLinesToDb('GeoLiteCity-Location.csv', 'tabela1');
$testar_classe->insertLinesToDb('GeoLiteCity-Blocks.csv', 'tabela2');
$testar_classe->deleteFileFromDisk($testar_classe->obtainDownloadFileName());
$testar_classe->deleteFileFromDisk('GeoLiteCity-Blocks.csv');
$testar_classe->deleteFileFromDisk('GeoLiteCity-Location.csv'); 

Which is the best way of handle this? Create a new method to take care of the exceptions? There are any examples on how to do this?

Best Regards.

  • 写回答

6条回答 默认 最新

  • doudiecai1572 2010-12-22 14:13
    关注

    I'd advice looking into concept of exceptions in PHP. It makes code much clearer and it's more powerful than if..else statements everywhere.

    In your specific case, I'd just throw exception in your function if deleting of file fails and then use it in try..catch statement somewhere else.

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器