dsizd368332 2010-08-10 17:53
浏览 263
已采纳

函数多次返回

Is it possible to have a function with 2 returns like this:

function test($testvar)
{
  // do something

  return $var1;
  return $var2;
}

If so, how would I be able to get each return separately?

  • 写回答

30条回答 默认 最新

  • doushao1948 2010-08-10 17:59
    关注

    There is no way of returning 2 variables. Although, you can propagate an array and return it; create a conditional to return a dynamic variable, etc.

    For instance, this function would return $var2

    function wtf($blahblah = true) {
        $var1 = "ONe";
        $var2 = "tWo";
    
        if($blahblah === true) {
          return $var2;
        }
        return $var1;
    }
    

    In application:

    echo wtf();
    //would echo: tWo
    echo wtf("not true, this is false");
    //would echo: ONe
    

    If you wanted them both, you could modify the function a bit

    function wtf($blahblah = true) {
        $var1 = "ONe";
        $var2 = "tWo";
    
        if($blahblah === true) {
          return $var2;
        }
    
        if($blahblah == "both") {
          return array($var1, $var2);
        }
    
        return $var1;
    }
    
    echo wtf("both")[0]
    //would echo: ONe
    echo wtf("both")[1]
    //would echo: tWo
    
    list($first, $second) = wtf("both")
    // value of $first would be $var1, value of $second would be $var2
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题