PHP中||与\&\&优先级小对比

今天在工作中看了一下同事代码,大概是这个样子:

if(($name == 'tancy' || $email == '[email protected]') && $age == '24'){......}

写法和程序都没有问题,但是我突然勾起了我的探究心理,虽然不是特别重要的问题,但是还是研究了一下,所以来分享一下过程:

以以下代码为基础:

<?php
$name = 'tancy';

$email = '[email protected]';

$age = '24';

if($name == 'tancy' || $email == '[email protected]' && $age == '24'){
    echo 'true';
}else{
    echo 'error';
}
?>


按照上面情况页面肯定输出:true,我们都知道,在php中||的优先级比&&高,所以我们可以探索一下上面语法的执行过程:

当函数执行到if语句时,根据优先级的关系,所以会先执行$email == '[email protected]' && $age == '24'语句,根据上面变量的赋值关系,这时会返回true,然后会执行$name == 'tancy' || true,当然肯定返回的是true,那么最终的输出结果是true。

然后我们先把$name的值改成错误的,比如:if($name == 'tom' || $email == '[email protected]' && $age == '24'){......},那执行过程就是先执行$email == '[email protected]' && $age == '24',返回值true,然后$name == 'tom' || true,这时无论$name == 'tom'是否正确,返回值肯定为true

<?php
$name = 'tancy';

$email = '[email protected]';

$age = '24';

if($name == 'tom' || $email == '[email protected]' && $age == '24'){
    echo 'true';
}else{
    echo 'error';
}
?>

2.然后我们把if语句中的优先级给他变换一下(加括号),像这样:if(($name == 'tancy' || $email == '[email protected]') && $age == '24'){......},那么返回结果还是true,执行过程:

虽然&&的优先级比||高,但是括号的更高,所以先执行括号里面的内容($name == 'tancy' || $email == '[email protected]'),当然返回结果肯定是true,再执行true && $age == '24',最终结果肯定是ture

<?php
$name = 'tancy';

$email = '[email protected]';

$age = '24';

if(($name == 'tancy' || $email == '[email protected]') && $age == '24'){
    echo 'true';
}else{
    echo 'error';
}
?>

3.最后我们把$name的值改成错误的,比如:if(($name == 'tom' || $email == '[email protected]') && $age == '24'){......},那执行过程就是先执行$name == 'tom' || $email == '[email protected]',返回值true,然后true && $age == '24',这时无论$name == 'tom'是否正确,返回值肯定为true

<?php
$name = 'tancy';

$email = '[email protected]';

$age = '24';

if(($name == 'tom' || $email == '[email protected]') && $age == '24'){
    echo 'true';
}else{
    echo 'error';
}
?>
扫描二维码关注公众号,回复: 2779314 查看本文章

猜你喜欢

转载自blog.csdn.net/tancy_weipj/article/details/50997031
今日推荐