dongxiong1935 2016-03-30 14:11 采纳率: 0%
浏览 14
已采纳

无法用三元运算符复制条件

I'm trying to replicate this condition:

$sth = $this->getResult();
if($sth !== true){
   return $sth;
}

with ternary operator I tried with;

($sth !== true) ?  return $sth : ($sth == true) ? null;

But I got:

Expected colon

  • 写回答

5条回答 默认 最新

  • doumengjing1500 2016-03-30 14:21
    关注

    What you're ultimately trying to achieve is not possible with a ternary operator.

    What you try to do is ONLY return in 1 situation, and continue the code in the other. The only way you could do this using a ternary operator is like this:

    $result = ($sth !== true) ? true : false;
    if ($result) return;
    

    But that kinda defeats the purpose of the ternary operator.


    In fact, your code has a couple of problems:

    • Ternary operator always needs 3 parts (*)
    • There is no need to check a condition twice, as that's the entire point of the operator
    • The operator returns a value, so you can't put a return inside the truthy or falsy part.

    A ternary operator needs 3 parts

    (condition) ? truthy result : falsy result
    

    Note: 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. - source: php.net

    No need to check things twice:

    Again, let's take our operator:

    ($sth !== true)
                    ? "I return if '$sth' is not true"
                    : "I return if '$sth' is true";
    

    There is no need to have a 2nd check. You have both situations covered already. :)

    No return values inside the truthy or falsy part

    Finally: it is an operator that returns a value. You can't put a return in the truthy or falsy part, you need to put it in front of it:

    return ($sth !== true)
                    ? "I return if '$sth' is not true"
                    : "I return if '$sth' is true";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥15 小红薯封设备能解决的来
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'
  • ¥15 vue+element项目中多tag时,切换Tab时iframe套第三方html页面需要实现不刷新
  • ¥50 深度强化学习解决能源调度问题
  • ¥15 一道计算机组成原理问题