本文介绍了PHP - Validation函数返回true | false,如果为false则返回一条消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个验证函数返回 true
或 false
。
但是,我希望它提供有关问题是什么的信息,当有一个。
让我们说这个函数是这样的:
函数is_valid($ val){
$ result = true;
if(rule_1_not_met)$ result = false;
if(rule_2_not_met)$ result = false;
返回$ result;
}
使用这种方式
$ val = $ _GET ['some_param'];
if(!is_valid($ val))$ out。='没有那么有用的反馈。
...
我想我可以像这样改变它:
函数is_valid($ val){
$ result = array(true,array());
if(rule_1_not_met)$ result [1] [] ='Reason 1';
if(rule_2_not_met)$ result [1] [] ='原因2';
if(count($ result [1])> 0)$ result [0] = false;
返回$ result;
}
并像这样使用它:
$ val = $ _GET ['some_param'];
$ validation_result = is_valid($ val);
if(!$ validation_result [0])$ out。= implode('< br />',$ validation_result [1]);
...
我的问题是
- 我是否有意想不到的结果?
- 有没有更好的方法来实现这个目标?
PS将使这个社区维基
解决方案
你在正确的轨道,但我想这样做
函数is_valid($ val,& $ mes){
$ result = true;
if(rule_1_not_met){$ mes [] ='message one'; $ result = false; }
if(rule_2_not_met){$ mes [] ='Message two'; $ result = false; }
返回$ result;
}
$ mes = array();
if(isvalid($ val,$ mes)=== false)$ out。= implode('< br />',$ mes);
I have a validation function which returns either true
or false
.
However, I want it to provide info as to what the problem is, when there is one.
Let's say the function is like this:
function is_valid($val) {
$result = true;
if( rule_1_not_met ) $result = false;
if( rule_2_not_met ) $result = false;
return $result;
}
Which is used like this
$val = $_GET['some_param'];
if(!is_valid($val)) $out .= 'Not so helpful feedback.';
...
I thought I could change it like this:
function is_valid($val) {
$result = array(true, array());
if( rule_1_not_met ) $result[1][] = 'Reason 1';
if( rule_2_not_met ) $result[1][] = 'Reason 2';
if(count($result[1]) > 0) $result[0] = false;
return $result;
}
And use it like this:
$val = $_GET['some_param'];
$validation_result = is_valid($val);
if(!$validation_result[0]) $out .= implode('<br/>', $validation_result[1]);
...
My question is
- Am I in, for unexpected results with this?
- Are there better ways to achieve this?
P.S. Would make this community wiki
解决方案
You are in the right track but I would like to do this in this way
function is_valid($val,&$mes) {
$result = true;
if( rule_1_not_met ) { $mes[]='message one'; $result = false; }
if( rule_2_not_met ) { $mes[]='Message two'; $result = false; }
return $result;
}
$mes=array();
if(isvalid($val,$mes) ===false) $out .= implode('<br/>', $mes);
这篇关于PHP - Validation函数返回true | false,如果为false则返回一条消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!