如何执行此PHP switch语句?
还要注意的是,这些是小得多的版本,我需要创建的1将有更多的值添加到它。
版本1:
switch ($p) { 
    case 'home': 
    case '': 
        $current_home = 'current';
    break; 
    case 'users.online': 
    case 'users.location': 
    case 'users.featured': 
    case 'users.new': 
    case 'users.browse': 
    case 'users.search': 
    case 'users.staff': 
        $current_users = 'current';
    break;
    case 'forum': 
        $current_forum = 'current';
    break; 
} 版本2:
switch ($p) { 
    case 'home': 
        $current_home = 'current';
    break; 
    case 'users.online' || 'users.location' || 'users.featured' || 'users.browse' || 'users.search' || 'users.staff': 
        $current_users = 'current';
    break;
    case 'forum': 
        $current_forum = 'current';
    break; 
} 更新-测试结果
我在10,000次迭代中运行了一些速度测试,
Time1: 0.0199389457703 // If语句
Time2: 0.0389049446106 //开关语句
Time3: 0.106977939606 //数组
发布于 2012-11-17 04:06:04
交换机与相结合将为您提供更大的灵活性:
<?php
$p = 'home'; //For testing
$p = ( strpos($p, 'users') !== false? 'users': $p);
switch ($p) { 
    default:
        $varContainer = 'current_' . $p; //Stores the variable [$current_"xyORz"] into $varContainer
        ${$varContainer} = 'current'; //Sets the VALUE of [$current_"xyORz"] to 'current'
    break;
}
//For testing
echo $current_home;
?>要了解更多信息,请查看variable variables和我提交给php手册的示例:
示例1:http://www.php.net/manual/en/language.variables.variable.php#105293
示例2:http://www.php.net/manual/en/language.variables.variable.php#105282
PS:这个示例代码是小而简单的,正是我喜欢的方式。它已经过测试,也可以正常工作
https://stackoverflow.com/questions/1309728
复制相似问题