try...catch
只有當你的函數拋出異常時纔有意義。如果他們不這樣做,那麼catch
就沒有什麼了。我想這個開始的重構:
$results = mysql_query($query);
if (!mysql_num_rows($results)) {
echo 'No results!';
exit;
}
$ids = array();
while (($result = mysql_fetch_row($results)) !== false) {
$ids[] = $result['id'];
}
$ids = array_map('mysql_real_escape_string', $ids);
$query = "DELETE FROM table1 WHERE id IN ('" . join("','", $ids) . "')";
if (!mysql_query($query)) {
echo mysql_error();
exit;
}
$query = "DELETE FROM table2 WHERE id = '$id'";
if (!mysql_query($query)) {
echo mysql_error();
exit;
}
header("Location: list.php?m=4");
exit;
這能夠進一步提高了很多,但它已經在你的麪條邏輯的改善。如果你對正確使用異常很感興趣,你應該首先繼續正確使用重複任務的函數(如error, exit
部分),然後可能將整個事物重構爲類和對象,最後使用異常來在現在嵌套圖層。也許開始使用PHP框架來感受整個事物。
把異常轉換成上面的代碼將很難超過goto
多,但只是用於說明目的:
try {
$results = mysql_query($query);
if (!mysql_num_rows($results)) {
throw new Exception('No results!');
}
$ids = array();
while (($result = mysql_fetch_row($results)) !== false) {
$ids[] = $result['id'];
}
$ids = array_map('mysql_real_escape_string', $ids);
$query = "DELETE FROM table1 WHERE id IN ('" . join("','", $ids) . "')";
if (!mysql_query($query)) {
throw new Exception(mysql_error());
}
$query = "DELETE FROM table2 WHERE id = '$id'";
if (!mysql_query($query)) {
throw new Exception(mysql_error());
}
header("Location: list.php?m=4");
exit;
} catch (Exception $e) {
echo 'ERROR: ' . $e->getMessage();
exit;
}
http://www.w3schools.com/php/php_exception.asp – ArK 2010-11-25 06:15:51
有你尚未嘗試?你不瞭解什麼部分?是的,錯誤處理是Exceptions的適當用法。 – Matthew 2010-11-25 06:16:26