donglin9068 2014-03-24 15:14
浏览 50
已采纳

返回语句简写语法[重复]

I am new to php developing but so far have been able to do whatever I want. I recently came across a strange syntax of writing a return statement:

public static function return_taxonomy_field_value( $value )
{ 
   return (! empty(self::$settings['tax_value']) ) ? self::$settings['tax_value'] : $value;
}

I get the return() and the !empty() but after that it has a ? and that's where I get lost. Any help is much appreciated! Thanks guys

</div>
  • 写回答

3条回答 默认 最新

  • douye4051 2014-03-24 15:18
    关注

    This is a ternary operator, a short version of the if statement.

    This:

    $a = $test ? $b : $c;
    

    is the same as:

    if($test)
    {
        $a=$b;
    }
    else
    {
        $a=$c;
    }
    

    so basically your example is equivalent to:

    if(! empty(self::$settings['tax_value'])
    {
        return self::$settings['tax_value'];
    }
    else
    {
        return $value;
    }
    

    You can find some more info here, together with some tips for precautions when using ternary operators.

    Important note about the difference from other languages

    Since the question is marked as a duplicate of another question that deals with ternary operator in Objective-C, I feel this difference needs to be addressed.

    The ternary operator in PHP has a different associativity than the one in C language (and all others as far as I know). To illustrate this, consider the following example:

    $val = "B";
    $choice = ( ($val == "A") ? 1 : ($val == "B") ? 2 : ($val == "C") ? 3 : 0 );
    echo $choice;
    

    The result of this code (in PHP) will be 3, even though it would seem that 2 should be the correct answer. This is due to weird associativity implementation that threats the upper expression as:

    ( ( ( ($val=="A") ? 1 : ($val=="B") ) ? 2 : ) ($val=="C") ? 3 : 0 )  
      ▲ ▲                               ▲       ▲  
      | |                               |       |  
      \  \_____________________________/        /  
       \_______________________________________/  
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口