PHP switch 语句不使用 return 执行值 [英] PHP switch statement doesn't executes values using return

查看:121
本文介绍了PHP switch 语句不使用 return 执行值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP switch 语句是否有可能在使用 return 时没有执行 switch 所需的结果?

Is it possible that PHP switch statement does not executes the switch desired result while using return?

这两种说法有什么区别?

What is the difference between these two statements?

$foo = '2';    
switch ($foo) {       
    case 1:
        echo 1;
        break;

    case 2:
        echo 2;
        break;
}

执行 2

对比

$foo = '2';    
switch ($foo) {       
    case 1:
        return 1;
        break;

    case 2:
        return 2;
        break;
}

似乎不起作用.

有没有办法让它工作?

推荐答案

这里是如何在函数中使用 case 语句 -

Here is how to use a case statement in a function -

function myFunction($foo) {
    switch ($foo) {       
        case 1:
            return 1;
            break;

        case 2:
            return 2;
            break;

        default:
            return 'no matching values were sent to the function';
            break;
    }
}

echo myFunction(2); // will echo '2'

在这样的函数中,你不需要 break 语句,return 负责中断.这只是很好的做法.您应该养成在开关中使用默认情况的习惯,即使您仅使用它们将错误记录到日志或类似内容中.

In functions like this you do not need to have the break statements, the return takes care of the breaking. It is just good practice. You should get in the habit of using default cases in your switches, even if you only use them to record an error to a log or something similar.

这篇关于PHP switch 语句不使用 return 执行值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆