PHP-添加变量以切换语句值


PHP - Add variable to switch statement value

我有以下switch语句:

$html = '<div class="'. $some_value . '">';
switch ($some_value) {
    case "one":
        return $html . 'One Biscuit</div>';
        break;
    case "two":
        return $html . 'Two Chimps</div>';
        break;
    case "three":
        return $html . 'Three Pies</div>';
        break;
    default:
        return $html . 'Meh...</div>';
}

注意到我是如何将$html变量添加到每个案例中的吗?不好。。。是否可以将其添加到switch语句的最终值中一次?我正在尝试将最终值包装在动态HTML中。

这个怎么样:

switch($some_value){
    case 'one':
        $var="One Biscuit";
    break;
    case 'two':
        $var="Two Chimps";
    break;
    case 'three':
        $var="Three Pies";
    break;
    default:
        $var="Meh...";
    break;
}
$html="<div class=".$some_value.">".$var."</div>";

将字符串存储在新变量中。此外,您不需要在返回语句之后中断

$html = '<div class="'. $some_value . '">';
$str = null;
switch ($some_value) {
    case "one":
        $str = 'One Biscuit</div>';
        break;
    case "two":
        $str = 'Two Chimps</div>';
        break;
    case "three":
        $str = 'Three Pies</div>';
        break;
    default:
        $str = 'Meh...</div>';
        break;
}
return $html.$str;

一种方法:

$html = '<div class="'. $some_value . '">';
$v = 'Meh...</div>';
switch ($some_value) {
    case "one":
        $v = 'One Biscuit</div>';
        break;
    case "two":
        $v = 'Two Chimps</div>';
        break;
    case "three":
        $v = 'Three Pies</div>';
        break;
}
$html .= $v;

由于您使用的是return,因此您最终只能返回一次:return $html.$v

此外,您还可以将参数定义为默认值,如下所示:

function someFunction(DUNNO_YOUR_PARAMS, $v = 'Meh...'){
    $v .= '</div'>;
    // rest of code

其他方法是在数组中保存数据:

$some_value = 'two';
//
$data = array(//this data could be stored in a database table
  'one'  => 'One Biscuit',
  'two'  => 'Two Chimps',
  'three'=> 'Three Pies',
  'default' => 'Meh...'
);
$html = '<div class="'.$some_value.'">'.(isset($data[$some_value])?$data[$some_value]:$data['default']).'</div>';
var_dump($html);

结果:

string '<div class="two">Two Chimps</div>' (length=33)

在某些情况下,数组比开关更快:在PHP中,what';s更快、更大的Switch语句或数组关键字查找

如果html较长,另一个可能更容易维护的解决方案:

<?php
ob_start();
echo '<div class="'.$some_var.'">';
/*
Be sure the file exists in the location you want
You can change items to the name of any directory you want just be
sure the file exists in the end. In the case of linux be sure the file
is the exact same name...
*/
include('items/'.$some_var.'.php');
echo '</div>';
$output = ob_get_clean();
return $output;
?>

在你的文件中,你只需要放入你想要的html代码
示例three.php(它实际上只是html或纯文本,除非你处理一些东西:

Three pies

如果你有太多这么简单的文件,这可能是可以重构的。但在更复杂的情况下,你可以包括更多的东西。