这可以写得更好吗? PHP代码
问题描述:
我正在尝试生成最终字符串以显示基于某些条件的用户。这可以写得更好吗? PHP代码
$flag=0;
$var='Please ';
if($user->is_details_updated == 'N' && $user->needs_to_update_details == "Y")
{
$var='update your profile details';
$flag=1;
}
if ($flag ==1)
{
$var=' and ';
}
if($user->is_pass_changed == 'N' && $user->needs_to_update_password == "Y")
{
$var.='change password';
}
所以,如果三个if
回报true
然后最终$var
看起来是这样的:
请更新您的个人资料详细信息和更改密码
这可怎么写比较好?
答
您可以邮件添加到阵列,然后用and
$var = arrray()
if($user->is_details_updated == 'N' && $user->needs_to_update_details == "Y")
{
$var[] ='update your profile details';
}
if($user->is_pass_changed == 'N' && $user->needs_to_update_password == "Y")
{
$var[]='change password';
}
echo join(" and ", $var);
答
如何加入他们:
$sayings = array();
if($user->is_details_updated == 'N' && $user->needs_to_update_details == "Y") {
$sayings[] = 'update your profile details';
}
if($user->is_pass_changed == 'N' && $user->needs_to_update_password == "Y") {
$sayings[] = 'change password';
}
$var = 'Please ' . implode(' and ', $sayings);
答
另一项建议是(如果可能的话),以重构$user->is_details_updated
,$user->needs_to_update_details
,$user->is_pass_changed
, $user->needs_to_update_password
属性返回布尔值true
/false
值。这可能会在稍后节省一些调试头痛。
你可以在[Code Review](http://codereview.stackexchange.com/)上发表 - 另一个StackExchange页面,这个问题比这里更适合。 – Xaerxess 2011-06-03 11:42:08