doubi7496 2017-05-25 04:32 采纳率: 0%
浏览 76
已采纳

PHP:在if语句中分配多个变量

I don't seem to be able to assign multiple variables in an "if" statement. The following code:

<?php

function a ($var)
{
    if ($var == 1)
    {
        return 'foo';
    }

    return false;
}

function b ($var)
{
    if ($var == 1)
    {
        return 'bar';
    }

    return false;
}

if ($result1 = a(1) && $result2 = b(1))
{
    echo $result1 . ' ' . $result2;
}

?>

Returns "1 bar" rather than "foo bar". If I remove the second condition/assignment it returns "foo".

Is there a way to assign multiple variables in an "if" statement or are we limited to just one?

  • 写回答

4条回答 默认 最新

  • dousao9569 2017-05-25 04:35
    关注

    This is all about operator precedence

    <?php
    
    function a ($var)
    {
        if ($var == 1)
        {
            return 'foo';
        }
    
        return false;
    }
    
    function b ($var)
    {
        if ($var == 1)
        {
            return 'bar';
        }
    
        return false;
    }
    
    if (($result1 = a(1)) && ($result2 = b(1)))
    {
        echo $result1 . ' ' . $result2;
    }
    
    ?>
    

    https://repl.it/IQcU

    UPDATE

    assignment operator = is right-asscoiative, that means,

    $result1 = a(1) && $result2 = b(1)
    

    is equivalent of,

    $result1 = (a(1) && $result2 = b(1))
    

    which evaluates

    $result1 = ("foo" && [other valild assignment] )
    

    which will result that,

    $result1 becomes true

    and echo true/string value of boolean true (strval(true)) outputs/is 1

    you can also check that revision, https://repl.it/IQcU/1

    to see that below statement

    $result1 = a(1) && $result2 = b(1)  
    

    is equivalent of this one.

     $result1 = (a(1) && $result2 = b(1)) 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题