[英]How better this can be written? PHP code
我正在嘗試生成最終字符串以根據某些條件向用戶顯示。
$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
屬性以返回 boolean true
/ false
值。 這可能會在以后節省一些調試麻煩。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.