【发布时间】:2019-08-24 11:20:09
【问题描述】:
我有一个包含许多函数的类,用于提交和从 MySql 数据库中选择数据。为了节省时间,我需要一个try-catch 块来捕获类中的所有异常。
我在下面尝试了我的代码,但它不起作用,因为 try 块给出了语法错误。
class DB_FunctWeb {
public $db;
//my try block starts
try {
function __construct($conn) {
$this->$db=$conn;
}
function __destruct() {
}
//....more functions....
} catch (Exception $e) {
$errnumber = $db->errno;
header("./creator.php");
if ($errnumber === 1062) {
insertInfo(" Duplicate entry please re-enter farm name.");
// echo $e->getMessage();
} else {
insertInfo(" An error occurred. Items where not added.");
}
} finally {
closeconn($db);
mysqli_report(MYSQLI_REPORT_OFF);
}
}
问题
如何在类中捕获异常?
【问题讨论】:
-
每个函数都需要自己的 try/catch 块
-
@Nick 没有其他方法可以为所有人添加一个
try-catch块吗?例如包含一个带有try-catch的文件,并在try-catch块之间调用所有函数,或者我读到了一些关于__call方法的内容,这也是一个选项。 -
如果您将所有方法声明为私有,您可以使用
__call拦截调用,并使用它在函数调用周围包装try/catch。可能是public function __call($name, $arguments) { try { $this->$name(...$arguments); } catch (Exception $e) { echo "error!"; } }之类的? -
@Nick 谢谢!这澄清了一些不确定性。在尝试之前,首先必须了解更多。
标签: php exception try-catch php-7