【问题标题】:shorthand for if else statement assigning value to variableif else 语句为变量赋值的简写
【发布时间】:2015-11-09 03:24:20
【问题描述】:

哈,为什么名称显示值1

['name' => ($profile->getNickname() || $profile->getName()),]

a => b || C 如果 b 为空,使用 c 不是吗?

附言我知道我可以做普通的 if else 速记(三元),但它又长又不可读,我不喜欢它。

【问题讨论】:

  • 这是一个普通的逻辑或运算符。因此,如果您的第一个函数返回 FALSE 而第二个函数返回 TRUE,那么它将像这样评估:FALSE || TRUE -> TRUE
  • 是的,我明白了。但在 ruby​​ 中,我可以这样做并根据比较为 var 赋值。
  • 需要专门使用empty函数
  • @anurupr 哦,真的不是红宝石吗?它在许多语言中都很常见

标签: php


【解决方案1】:

在 javascript 中这是很常见的写法,但 PHP 会转换为布尔值。

这个问题将回答你的问题:Best way to give a variable a default value (simulate Perl ||, ||= )

$name = $profile->getNickname() ?: $profile->getName();

【讨论】:

  • 太棒了。这就是我要找的:)
  • 这里要注意:返回值不能是:FALSE、0、NULL、""或任何其他错误值。
  • @Rizier123 对,完全等同于 OP 在其他语言中熟悉的非布尔值 ||
  • 在 PHP 7 中,您还可以使用 Null Coalescing Operator (??) $name = $profile->getNickname() ?? $profile->getName(); 因此,当第一个条件未定义或错误地没有异常/错误时,这将起作用跨度>
【解决方案2】:

在 PHP 中,布尔运算符 ||&& 总是产生一个布尔值;如有必要,操作数被强制为布尔值,并丢弃原始值。这与 JavaScript 不同,在 JavaScript 中,操作数被评估为“真实性”,但保留其原始值。

您看到的 1 只是因为您回显了一个布尔值,这反过来将 true 强制转换为字符串 1

PHP 确实有一个您想要的简写运算符:?:

【讨论】:

    【解决方案3】:

    ($profile->getNickname() || $profile->getName()) 只是一个实现的条件 (1),这就是它显示 1 的原因。

    应该是这样的:

    // if nick name is set and not empty then show it otherwise show name
    [ 'name' => ((isset($profile->getNickname()) && ($profile->getNickname() != "")) ?  $profile->getNickname() : $profile->getName())]
    

    【讨论】:

    • 您希望如何维护这种代码? :)
    【解决方案4】:

    如果 isset(data)
    $profile->getNickname()
    $profile->getName() 从函数返回布尔值br> 决定一个条件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 2012-04-09
      • 1970-01-01
      • 1970-01-01
      • 2017-02-25
      • 2021-08-13
      • 2019-03-06
      相关资源
      最近更新 更多