想知道 Laravel 8 中哪種解決方案更好我需要顯示名稱 = company_name 如果它不為空 / OR =user_name 如果 company_name 為空 OR = first_name last_name OR email
我的代碼
public function getDisplayName($email = false)
{
$name = $this->name??"";
if(!empty($this->business_name) ){
$name = $this->business_name;
}
elseif(!empty($this->user_name) ){
$name = $this->user_name;
}
elseif (!empty($this->first_name) or !empty($this->last_name)) {
$name = implode(' ', [$this->first_name, $this->last_name]);
}
elseif(!trim($name) and $email) $name = $this->email;
else (empty($name)){
$name = ' ';
}
return $name;
}
將它用于所有情況或 ifelse 在我的代碼中會更好嗎?謝謝
uj5u.com熱心網友回復:
如果將return陳述句放在if()條件中,則可以使用簡單的if (...) { return ... }語法:
public function getDisplayName($email = ' ') {
if (!empty($this->business_name)) {
return $this->business_name;
}
if (!empty($this->user_name)) {
return $this->user_name;
}
return trim("{$this->first_name} {$this->last_name}") ?? $email;
}
使用此代碼,將回傳、 then 、 and 、then business_name、then finallyuser_name的組合。如果您只是要在函式結束時回傳它,那么在此處分配并沒有多大用處,您可以簡單地將最終默認設定為并且您很好。first_namelast_name$email' '$name$email = ' ';
uj5u.com熱心網友回復:
您可以使用Null 合并運算子。
已添加空合并運算子 (??) 作為語法糖,用于需要將三元組與 isset() 結合使用的常見情況。如果存在且不為空,則回傳其第一個運算元;否則回傳第二個運算元。
public function getDisplayName($email = false)
{
return $this->business_name
?? $this->user_name
?? trim(implode(' ', [$this->first_name, $this->last_name]))
?? $this->email
?? ' ';
}
我給您留下另一個對您有用的檔案鏈接。
uj5u.com熱心網友回復:
刀刃
@if($itams->count() > 0)
@else
@endif
其他
if($this->id == 1)
{
return
} else {
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/447153.html
上一篇:設計模式之外觀模式
