包含文件中是否可能包含不完整的语句。 例如就我而言,我想重复这段代码->
case "c":
case "d":
case "e":
我将其放置在包含文件file.inc.php
中<?php
case "c":
case "d":
case "e":
,正常的运行代码是这样的:
switch {
case "a":
case "b":
//something gets done here!
break;
include ('file.inc.php');
//do something here - doesn't work tho
break;
}
可以做到吗?从我所看到的,我什至不确定包含文件是否包含在内?开关仅查找a和b,没有错误。
答案 0 :(得分:-1)
请阅读php手册以了解开关情况。我认为您的代码无法使用这种语法。
https://www.php.net/manual/en/control-structures.switch.php
switch {
case "a":
case "b":
//something gets done here!
break;
case "c":
include ('file.inc.php');
//do something here - doesn't work tho
break;
}
答案 1 :(得分:-1)
是否可以将案例导入切换块?
您应该实施吗?
正如我之前许多人所强调的那样,eval()
是“邪恶的”,并且闪烁着巨大的征兆,即您的项目结构有些尴尬/不合适。最后,您应该花时间重构项目,以便不再需要此技术。
现在,为了证明这是可能的...一种解决方法是将include()
调用替换为file_get_contents
调用以获取包含文件的内容,并将该字符串作为一个完整字符串插入switch()
使用eval()
进行阻止。
经过测试的代码:
broken_switch.php
<?php
$includedCases = file_get_contents('evaled.inc.php');
foreach (['a', 'b', 'c', 'd', 'e', 'f'] as $letter) {
echo "<div> $letter => ";
eval('
switch ($letter) {
case "a":
case "b":
echo "switch value satisfied by a or b as normal";
break;
?>' . $includedCases . '
echo "switch value satisfied by c, d, or e from eval\'ed include file";
break;
default:
echo "default case";
}
');
echo "</div>";
}
evaled.inc.php
<?php
case "c":
case "d":
case "e":
broken_switch.php 的输出:
a => switch value satisfied by a or b as normal
b => switch value satisfied by a or b as normal
c => switch value satisfied by c, d, or e from eval'ed include file
d => switch value satisfied by c, d, or e from eval'ed include file
e => switch value satisfied by c, d, or e from eval'ed include file
f => default case
这只是一个示范。我不会打扰“优化”,因为我要指出的是该技术不应实施。