php - 在不同的文件中拆分开关案例

标签 php switch-statement

我有一个 php 文件,我在其中使用了一个非常长的开关盒。我想将案例拆分到不同的文件中(将逻辑上相关的案例保存在 1 个文件中)。

编辑:对不起大家,是我的代码导致了问题。开关盒按预期工作。

文件 -> a.php

echo "<br>RES = ".test(1);

function test($value) {
    switch($value) {
        case (1 || 2):
                include("b.php");
                            **return $temp;**
                break;

        default: echo "error";
                return 3;
                break;
    }
}

文件 -> b.php

switch($value) {

    case 1: echo "value is 1";
                    **$temp = 1;**
            return 1;
            break;

    case 2: echo "value is 2";
                    **$temp = 2;**
                    return 2;
                    break;
}

如何获得正确的结果?如果 b.php 的开关盒在 a.php 文件中,那么一切正常。关于如何执行此操作的任何想法/建议?

如果我添加 $temp(粗线)那么它就可以工作...

提前感谢您的帮助。

问候

最佳答案

更新问题的更新回复: 修改“a.php”并在“b.php”前面添加一个返回前缀包括:

return include("b.php");

http://www.php.net/manual/en/function.include.php

Handling Returns: It is possible to execute a return() statement inside an included file in order to terminate processing in that file and return to the script which called it. Also, it's possible to return values from included files. You can take the value of the include call as you would a normal function. This is not, however, possible when including remote files unless the output of the remote file has valid PHP start and end tags (as with any local file). You can declare the needed variables within those tags and they will be introduced at whichever point the file was included.


在您的 case/break 部分中使用简单的 include()?

switch($var)
{
 case 1:
   include('case_1.php');
   break;
 case 2:
   include('case_2.php');
   break;
 default:
   include('case_default.php');
  break;
}

关于php - 在不同的文件中拆分开关案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6543072/

相关文章:

c# - 带有非常量表达式的 Switch 语句 - 扩展 C#/IDE 能力

java - 在 switch case 中使用枚举,但不作为 switch 参数

java - 反编译后$SwitchMap$错误

php - 使用 Active Record 在 Yii 中调用数据库 View

php - 当在 joomla 中删除上传的文件时,从 id 数组中删除上传的文件吗?

php - 重定向到在 Laravel 5 中不起作用的路由

php - laravel dompdf 获取base64格式

javascript - Opcache、APC 或 Session.Upload_Progress 用于从单个文件输入上传多个文件

c# - 具有 boolean 值的开关盒的奇怪行为

python - 字典或 If 语句,Jython