建站视频教程全套 asp网站源码网页制作设计建设视频教程百度云/微信搜一搜怎么做推广
我要说的是返回布尔值和其他东西的前提是错误的.
功能应该有明确的目的,结果清晰.如果可以实现此结果,则返回结果.如果无法实现结果,则该函数返回false或抛出异常.哪个更好取决于情况和您的一般错误处理理念.无论哪种方式,让函数返回错误消息通常都没有用.该消息对调用该函数的代码没有用.
除了返回错误结果之外,PHP还有自己的输出错误消息的机制:trigger_error.它纯粹是一个帮助调试的工具,它不会取代标准的返回值.它非常适合您希望显示错误消息但仅仅是为了帮助开发人员的情况.
如果函数足够复杂,可能导致需要以不同方式处理的几种不同类型的错误,则应使用异常来执行此操作.
例如,一个非常简单的函数,其目的明确只需要返回true或false:
function isUserLoggedIn() {
return $this->user == 'logged in';
}
具有可能无法实现该目的的功能:
function convertToFoo($bar) {
if (!is_int($bar)) {
return false;
}
// here be dragons
return $foo;
}
同样的函数也会触发消息,对调试很有用:
function convertToFoo($bar) {
if (!is_int($bar)) {
trigger_error('$bar must be an int', E_USER_WARNING);
return false;
}
// here be dragons
return $foo;
}
可能合法地遇到调用代码需要知道的几种不同类型错误的函数:
function httpRequest($url) {
...
if (/* could not connect */) {
throw new CouldNotConnectException('Response code: ' . $code);
}
...
if (/* 404 */) {
throw new PageNotFoundException('Page not found for ' . $url);
}
return true;
}
我也会在这里粘贴此评论:
It should not be the responsibility of the function to prepare, return or display an end-user error message. If the purpose of the function is to, say, fetch something from the database, then displaying error messages is none of its business. The code that called the fetch-from-database function merely needs to be informed of the result; from here there needs to be code whose sole job it is to display an error message in case the database function cannot get the required information. Don’t mix those two responsibilities.