gpt4 book ai didi

php - 返回混合错误和 bool 值的替代方法

转载 作者:可可西里 更新时间:2023-10-31 22:49:50 24 4
gpt4 key购买 nike

我有一种(常见)情况,我当前返回的结果是混合类型,有时是 bool 值,有时是错误消息。例如:

function checked_thing_is_legal(){
// Do stuff and check for errors in here.
} // Returns true if there are no errors, otherwise returns an error message string.

这感觉很脏,有人曾经说过“将代码提炼成单一、可靠的返回值很好”,我认为这是很好的建议。那么检查错误的更好范例是什么?

最佳答案

我在这里看到两个选项

使用原子( bool )验证器并将错误消息与验证器本身分离

   if(!is_valid_email(blah)) print "invalid email";

将验证器对象与 boolean test() 和 string error() 函数一起使用:

$v = new SomeValidator;
if(!$v->test(blah))
echo $v->error();

在一个快速而肮脏的应用程序中,如果一切正常,您还可以考虑返回一个空值

 $err = validate_email(blah);
if(empty($err)) ok else print $err;

关于php - 返回混合错误和 bool 值的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1861845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com