>方法必须返回true或false
>方法必须返回true或错误消息
>方法必须返回true成功消息或false错误消息
> Method必须返回true成功结果(object,array,whatever)或false
>方法必须返回真正的成功结果(对象,数组,等等)或错误的错误消息
>等
我的问题是,当我在我的代码中使用这个类方法时,我总是要回到类中,并检查实际返回的方法是什么:只是true或false,true或错误消息等.
标准化返回值是个好主意吗?如果有,怎么样?
我的想法是:
>如果函数必须返回true或false,则只返回true或false
>如果函数必须返回true或错误消息,那么:
if (success) { return array( TRUE,null ); } else { return array( FALSE,$error_message ); }
if (success) { return array( TRUE,$success_message,); } else { return array( FALSE,$error_message ); }
>等
我希望你能理解我的问题,甚至认为我的解释不太好:)
您有什么建议或最佳做法?我该怎么处理?
更新:
我们举一个简单的例子:
function login($username,$password) { // Login logic here .. if ($logged_in) { return TRUE; } { return $error_message; } }
所以正确的方法是:返回true或抛出异常,并在调用login方法时执行try catch.因此,当出现问题(验证失败等)时,我应该使用异常.
功能应该有明确的目的,结果清晰.如果可以实现此结果,则返回结果.如果无法实现结果,则该函数返回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.