Php 重构简单函数
我需要以人类可读的格式显示当前记录状态。 在我的数据库中,这个字段有一个int,所以记录的状态可能是1、2、3、4 e.t.c 我编写了一些代码向用户显示当前状态:Php 重构简单函数,php,refactoring,Php,Refactoring,我需要以人类可读的格式显示当前记录状态。 在我的数据库中,这个字段有一个int,所以记录的状态可能是1、2、3、4 e.t.c 我编写了一些代码向用户显示当前状态: <?php // code to retrieve current status from DB // ... if ($status == '1') { echo "Current status: Active"; } if ($status == '2') { echo "Current status
<?php
// code to retrieve current status from DB
// ...
if ($status == '1') {
echo "Current status: Active";
}
if ($status == '2') {
echo "Current status: Pending";
}
if ($status == '3') {
echo "Current status: Inactive";
}
// etc..
?>
这段代码看起来很难看,但我不知道如何重构它以使其更有效,并且没有无限的条件。try语句
switch($status){
case '1':
echo "Current status: Active";
break;
case '2':
echo "Current status: Pending";
break;
case '3':
echo "Current status: Inactive";
break;
default:
echo "i is not equal to 1,2 or 3";
}
删除是因为。更好的方法是制作一个数组:
$statvalue=array(1=>'Active',2=>'Pending',3=>'Inactive');
echo("Current status: {$statvalue[$status]}");
最好使用数组解决此问题:
function foo($status) {
$strings = array(
'1' => "Current status: Active",
'2' => "Current status: Pending";
'3' => "Current status: Inactive";
);
return $strings[$status];
}
语法要短得多,您可以在以后通过向数组添加键来扩展它。您可以创建一个引用状态的数组:
<?php
$status_cases = ['active', 'pending', 'inactive'];
echo "Current status: ". $status_cases[$status - 1];
您可以做很多事情来改进这一点 首先,许多开发人员喜欢用常量值编写比较,如下所示:
if ('1' == $status) {
这使得意外地使用赋值运算符=而不是等式运算符==变得更加困难,后者往往会产生有趣的bug
其次,正如MortenSickel和Thomas Ruiz所写的,用查找替换这种语句是个好主意。MortenSickel的答案更好,因为这意味着您可以在数组中有间隙,而不必将数组填充与任意整数位置相协调-最好是显式的
然而,我的建议是将状态描述放在数据库中——很可能在几个地方需要这些信息——填充数据库的代码、读取数据库的代码、报告等等,跨多个代码位置协调这些信息听起来是个坏主意 制作一个数组:$statvalue=array'Active','Pending','Inactive',你应该编辑你的答案,将整数作为索引:array0=>Active',…Dale;有两个-你需要他们正确解析数组值,过去至少是这样请注意,短数组语法[]仅在PHP 5.4+中可用。是的,我认为最好了解最新的功能。当只是一个关于将数值映射到字符串的问题时,为什么要使用开关,使用阵列最容易完成哪一项?感谢您的详细回复!