Laravel 8if语句哪个更好

Laravel 8 If Statement which is better

想知道在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? 谢谢

如果将 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;
}

使用此代码,business_name,然后是 user_name,然后是 first_namelast_name 的组合,然后是 $email,最后是 ' ' 将被 returned。如果你只是想在函数末尾分配 return 的话,在这里分配 $name 没有多大用处,你可以简单地将最终默认值设置为 $email = ' '; 然后你很好

您可以使用 Null coalescing operator.

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not null; otherwise it returns its second operand.

public function getDisplayName($email = false)
{
    return $this->business_name
        ?? $this->user_name
        ?? trim(implode(' ', [$this->first_name, $this->last_name]))
        ?? $this->email
        ?? ' ';
}

我留给你另一个 document link 对你有用。