如果有条件的话,php变量赋值 [英] php variable assignment inside if conditional
问题描述
以下两个如果
s产生不同的结果(第一个如果
如果 echos hi,第二个没有),为什么?为什么 $ t
上的变量赋值不起作用?这是由于 $ t
的中的本地范围,如果
有条件的话?
The following two if
s produced different results(first if
echos second does not), why? why didn't the variable assignment on $t
work? is this due to $t
's local scope inside the if
conditional?
if(isset($_REQUEST["test"]) && $t=trim($_REQUEST["test"]) && !empty($t)){
echo 'hi'
}
if(isset($_REQUEST["test"]) && $t=trim($_REQUEST["test"])){
if(!empty($t))echo 'hi'
}
推荐答案
&&
has a higher precedence than =
, hence the first expression is evaluated as:
isset($_REQUEST['test']) && $t = (trim($_REQUEST['test']) && !empty($t))
由于!empty($ t)
在将任何内容分配给 $ t
之前进行评估,表达式为: 假
。您可以通过明确设置括号或使用不那么笨拙的方式来编写它来解决这个问题:
Since !empty($t)
is evaluated before anything is assigned to $t
, the expression is false
. You could fix this by explicitly setting parentheses, or by using a less awkward way to write it:
if (isset($_REQUEST['test']) && trim($_REQUEST['test'])) {
echo 'hi';
}
trim($ _ REQUEST ['test'])
将自行评估为 true
或 false
,无空
必要。如果你以后真的需要 trim
med值,你可以这样保存:
trim($_REQUEST['test'])
will evaluate to true
or false
just by itself, no empty
necessary. If you actually need the trim
med value later, you can save it like so:
if (isset($_REQUEST['test']) && ($t = trim($_REQUEST['test']))) {
echo 'hi';
}
这篇关于如果有条件的话,php变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!