我正在尝试更好地组织我的"操作",目前它是一个包含大量案例的巨大开关语句,而且很难管理。我想将操作移动到自己的文件中,以便更轻松地管理。但我正在尝试解决一个问题。
我有一个 foreach 循环,它遍历所有"被调用的操作"并调用它们。然后我有一堆动作,但有些动作我想结束当前循环的执行(即 continue;
或break;
),但这似乎不适用于包含的文件。
还有什么我能做到的吗?我还需要"操作"来访问执行脚本中定义的所有当前变量(这就是我选择包含的原因)。
现在。。。
included_file.php
<?php
blah blah stuff
if(statement) {
// accesses variables declared in calling_file.php
continue;
}
?>
calling_file.php
<?php
blah blah stuff
// declare variables that need to be accessed in included_files.php
foreach() {
include included_file.php
}
?>
现在对于一些操作,我想停止当前循环并进入下一个循环。有什么想法吗?
如果我正确理解您的问题,您似乎希望从包含的文件中获取一个结果,该结果指示您要做什么(break
,continue
),然后是一个简单的switch语句,以允许内部循环break
外部循环。中断控制结构将允许您执行此操作。
calling_file.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;
}
}
included_file1.php
<?php
print __FILE__ . " has been included!'n";
if(TRUE) {
print "I should continue!'n";
return CONTROL_CONTINUE;
}
included_file2.php
<?php
print __FILE__ . " has been included!'n";
if(TRUE) {
print "I should break!'n";
return CONTROL_BREAK;
}
included_file3.php
<?php
print __FILE__ . " has been included!'n";
if(TRUE) {
print "You should never see me!";
}