php - split switch cases in different files
I have a php file in which i am using a reall开发者_运维问答y very long switch case. I want to split the cases in different files (keep logically connected cases in 1 file).
EDIT: Sorry everyone it was my code that was causing problem. The switch case was working as expected.
file -> 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;
}
}
file -> 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;
}
How do i get proper result? if the switch case of b.php is in a.php file then everything works fine.Any idea/suggestion on how to do this?
If i add $temp (bold lines) then it works...
Thanks for help in advance.
Regards
Updated response to updated question: modify "a.php" and prefix a return infront of the "b.php" include:
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.
simple include()'s within your case/break sections?
switch($var)
{
case 1:
include('case_1.php');
break;
case 2:
include('case_2.php');
break;
default:
include('case_default.php');
break;
}
This is actually something that Scuzzy proposed (I have even left the same naming convention), but improved:
// list of files
$my_files = array(
'a' => 'case_1.php',
'b' => 'case_2.php',
'c' => 'case_3.php',
'd' => 'case_4.php',
);
// determine which one to load
if (array_key_exists($var, $my_files)) {
include($my_files[$var]);
} else {
include('case_default.php');
}
or even shorter ;) :
$f = array('a','b','c','d');
include((in_array($var,$f)?$var:'case_default').'.php');
switch($var)
{
case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: //...
include('case_' . $var . '.php');
break;
default:
include('case_default.php');
break;
}
精彩评论