0

我正在尝试更好地组织我的“动作”,目前它是一个带有大量案例的巨大 switch 语句,而且很难管理。我想将操作移动到可以更轻松管理的自己的文件中。但我正在尝试解决一个问题。

我有一个 foreach 循环,它遍历所有“被调用的动作”并调用它们。然后我有一堆动作,但有些动作我想结束当前循环的执行(即continue;break;),但这似乎不适用于包含的文件。

还有其他我可以做到的吗?我还需要“操作”来访问执行脚本中定义的所有当前变量(这就是我选择包含的原因)。

目前...

包含文件.php

<?php
blah blah stuff
if(statement) {
   // accesses variables declared in calling_file.php
   continue;
}
?>

调用文件.php

<?php
blah blah stuff
// declare variables that need to be accessed in included_files.php
foreach() {
include included_file.php
}
?>

现在对于某些操作,我想停止当前循环并进入下一个循环。有任何想法吗?

4

1 回答 1

0

如果我正确理解了您的问题,您似乎想从包含的文件中获得一个结果,该文件表明您想要做什么(break, continue),然后是一个简单的 switch 语句以允许内部循环到break外部循环。中断控制结构将允许您执行此操作。

调用文件.php

<?php

$includes = array ('included_file1.php', 'included_file2.php', 'included_file3.php');

const CONTROL_BREAK = 3;
const CONTROL_CONTINUE = 7;

// declare variables that need to be accessed in included_files.php
foreach($includes as $include) {
    print "Including $include\n";
    $result = include($include);
    switch ($result){
        case CONTROL_BREAK:
            break 2;

        case CONTROL_CONTINUE:

        default:
            continue 2;
    }
}

包含文件1.php

<?php
print __FILE__ . " has been included!\n";

if(TRUE) {
   print "I should continue!\n";
   return CONTROL_CONTINUE;
}

包含文件2.php

<?php
print __FILE__ . " has been included!\n";

if(TRUE) {
   print "I should break!\n";
   return CONTROL_BREAK;
}

包含文件3.php

<?php
print __FILE__ . " has been included!\n";

if(TRUE) {
   print "You should never see me!";
}
于 2013-09-11T15:43:54.740 回答