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条)

报告相同问题?

悬赏问题

  • ¥20 matlab如何绘制三维瀑布图
  • ¥15 关于用abap来解决动态规划的问题,但是要求输出索引值,这个是难点
  • ¥15 在ISIS中什么是IP从地址
  • ¥15 压测时,并发量过高时,响应时间出现尖刺
  • ¥15 关于vmprotect3.8.4虚拟文件一项
  • ¥15 在不用IT调试的情况下怎样能连外网
  • ¥20 C#调用虚拟键盘TabTip.exe
  • ¥15 Qt4代码实现下面的界面
  • ¥15 CCS离散化传递函数与仿真不一致
  • ¥15 prism提示我reinstall prism 如何解决