我使用 PDO 编写了一个新的数据库类。不过我正在努力解决一个问题。我通常返回一个对象,这样我就可以使用它。因此,当查询失败时,我只需返回 $this
。我有一个名为 wasSuccessful()
的方法,用于确保查询不会失败。
$result = $database->query(...);
if ($result->wasSuccessful()) {
// do code
}
但是,当该方法返回 false
时我该怎么办?例如:
...
if (!$this->tableExists($table)) return false;
发生这种情况时,PDO 告诉我无法对 bool 值运行函数。我该如何以最好的方式解决这个问题?
提前非常感谢!
最佳答案
您应该使用异常,而不是依赖函数的返回值。像这个简单的例子应该会给你这样的想法:
在你的类(class):
class MyClass {
public function query($sql, ...$params) {
if (!$this->tableExists($table)) {
throw new \Exception("the table doesn't exist");
return false;
}
}
}
然后在您的代码中:
try {
$result = $database->query(...);
// do stuff with $result, knowing it's ok
} catch (\Exception $e) {
echo "here's our error handling routine";
echo $e->getMessage();
}
在更复杂的项目中,可能需要创建自己的异常类。此外,您还可以在类中使用 try
/catch
,并将 PDO 中的异常抛出
到更高级别的代码。例如:
class MyClass {
public function query($sql, ...$params) {
if (!$this->tableExists($table)) {
throw new \Exception("the table doesn't exist");
return false;
}
try {
//do something with the PDO object that might throw an exception
} catch (\PDOException $e) {
// just take this existing exception and throw it to the next catch block
throw $e;
return false;
}
}
}
关于php - 我应该在 PDO 对象中返回什么来生成可靠的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55668177/