Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/251.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何以改进的方式完成此代码_Php_Switch Statement_Conditional Statements - Fatal编程技术网

Php 如何以改进的方式完成此代码

Php 如何以改进的方式完成此代码,php,switch-statement,conditional-statements,Php,Switch Statement,Conditional Statements,我想用正确的代码替换这里的switch语句。我需要一个改进方式的建议 switch(true) { case ($value === 'test1'): $testArray['class'] = 'incomplete'; return $this->icon( 'test_0.png', $testArray ); case ($value === 'test2'): $testArray['class']

我想用正确的代码替换这里的switch语句。我需要一个改进方式的建议

switch(true) {
    case ($value === 'test1'):
    $testArray['class'] = 'incomplete';
    return $this->icon(
        'test_0.png',
        $testArray
    );
    case ($value === 'test2'):
    $testArray['class'] = 'progress';
    return $this->icon(
        'test_1.png',
        $testArray
    );
    case ($value === 'test3'):
    $testArray['class'] = 'complete';
    return $this->icon(
        'test_3.png',
        $testArray
    );
}

尝试使用
'complete'
'progress'
'complete'
设置
$value
。将imgs重命名为
complete.png
progress.png
complete.png

然后这样做:

$testArray['class'] = $value; 
return $this->icon(
    $value.'.png',
    $testArray
);

这一切都取决于您设置
$value
的方式。但是,如果您设法以正确的方式设置,它将更短,更易于使用。

改进的switch语句是

    switch($value) {
    case 'test1':
        $testArray['class'] = 'incomplete';
        $image = 'test_0.png';
        break;
    case 'test2':
        $testArray['class'] = 'progress';
        $image = 'test_1.png';
        break;
    case 'test3':
        $testArray['class'] = 'complete';
        $image = 'test_3.png';
        break;
    default :
        break;
}
return $this->icon($image,$testArray);
或者,如果使用station

if ($value == 'test1') {
    $testArray['class'] = 'incomplete';
    $image = 'test_0.png';
} elseif ($value == 'test2') {
    $testArray['class'] = 'progress';
    $image = 'test_1.png';
} else {
    $testArray['class'] = 'complete';
    $image = 'test_3.png';
}

return $this->icon($image,$testArray);

使用if、else if和elseWhy你到底为什么要这样做而不是
开关($value){case'test1':…
看起来更适合: