【问题标题】:PHP switch statement function in OOP functionOOP函数中的PHP switch语句函数
【发布时间】:2015-03-02 18:52:16
【问题描述】:

今天早些时候,我向this question 询问了有关重新调整 switch 语句的输出的问题。

结论是 switch 语句中的 return 应该只在函数内部使用。

现在我正在尝试在类中的方法中使用返回。 这是代码:

class ClassName{

     public function www($foo)
     {
        switch ($foo) {       
            case 1:
                return '1';
                break;

            case 2:
                return '2';
                break;

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

$foo = 2;
ClassName::www($foo);

当我用 echo 替换返回时,我得到一个输出。 为什么它不能与 return 一起使用?

【问题讨论】:

  • 连同答案,你不需要那些breaks,因为 return 退出了开关和功能。

标签: php oop switch-statement return


【解决方案1】:

return 从字面上将值返回给调用代码,你必须实际对它做一些事情:

echo ClassName::www($foo);
//or
$val = ClassName::www($foo);
echo $val * 4;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    相关资源
    最近更新 更多