douren6035 2012-10-09 15:28
浏览 30
已采纳

我可以使用逻辑OR || 在PHP变量声明?

This code works:

$foo = getFoo();
if (!$foo) $foo = getBar();
if (!$foo) $foo = getJiggy();
if (!$foo) $foo = getWithIt();

I thought I'd seen somewhere a simplification of it with logical operators:

$foo = (getFoo() || getBar() || getJiggy() || ...);

I figured that the first true statement would get passed, but instead, it's just setting $foo to boolean true instead of the return value of getFoo(), getBar(), etc.

Is there a simplification like what I'm thinking of?

  • 写回答

6条回答 默认 最新

  • dqeonr8554 2012-10-09 15:38
    关注

    For JavaScript, foo = bar || baz; is a commonly used expression, as the || operator has a coalescing behavior.

    PHP does not have this behavior with regard to the || operator, which returns a boolean value. As such, the more verbose code you originally posted:

    $foo = getFoo();
    if (!$foo) $foo = getBar();
    if (!$foo) $foo = getJiggy();
    if (!$foo) $foo = getWithIt();
    

    is your most readable, and preferable option.

    PHP 5.3 has a shorthand version of the ternary operator, which acts as a coalescing operator:

    Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

    This would allow you to use:

    $foo = getFoo() ?: getBar() ?: getJiggy() ?: getWithIt();
    

    However, that assumes you don't have to worry about compatibility.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成