【问题标题】:How better this can be written? PHP code这可以写得更好吗? PHP 代码
【发布时间】:2011-06-03 11:34:51
【问题描述】:

我正在尝试根据某些条件生成最终字符串以显示用户。

$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 看起来像这样:

请更新您的个人资料并更改密码

如何写得更好?

【问题讨论】:

  • 您可以在Code Review 上发布此问题 - 另一个 StackExchange 页面,这个问题比这里更适合。

标签: php if-statement conditional-statements


【解决方案1】:

您可以将消息添加到数组中,然后使用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);

【讨论】:

  • 该死,刚刚被打败了...... +1 :)。
  • @skowron-line 请在 Stack Overflow 上开始使用“you”而不是“U”。此处明确禁止“聊天发言”。
  • @meagar 很抱歉我曾经这样写。但会改变它
【解决方案2】:

怎么样:

$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);

【讨论】:

    【解决方案3】:

    另一个建议是(如果可能的话)重构$user->is_details_updated$user->needs_to_update_details$user->is_pass_changed$user->needs_to_update_password 属性以返回布尔值true/false 值。这可能会在以后省去一些调试难题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多