【问题标题】:Shorthanded if statement have errors简写 if 语句有错误
【发布时间】:2017-01-04 12:00:00
【问题描述】:

我想简写 if 语句,但我的代码编辑器显示有错误。有什么问题?

我原来的 if 语句

<?php
 if($shippingCost["ShippingCost"]['shipping_type'] == 'order_sum') {
    echo $this->Format->money($shippingCost["ShippingCost"]['value_to']);
 } else {
    echo number_format($shippingCost["ShippingCost"]['value_to']);
 }
?>

我的简写版本

<?php
($shippingCost["ShippingCost"]['shipping_type'] == 'order_sum') ? //IDE error expected colon
echo $this->Format->money($shippingCost["ShippingCost"]['value_from']) : // IDE error expected semicolon
echo number_format($shippingCost["ShippingCost"]['value_from'])
?>

【问题讨论】:

  • echo a? a : b
  • 你真的不应该那样写。这看起来很糟糕
  • 您可以在手册中阅读它php.net/manual/en/… 但谁看手册。
  • 这不是一个有效的缩短代码,如果你想通过它使用 echo ...但它不会像这样工作

标签: php ternary-operator


【解决方案1】:

请注意echo 没有任何返回类型。这就是为什么你应该使用 print,或者在开头写 echo。

1.在开头使用 echo

echo ($shippingCost["ShippingCost"]['shipping_type'] == 'order_sum') ? 
    $this->Format->money($shippingCost["ShippingCost"]['value_from']) : 
    number_format($shippingCost["ShippingCost"]['value_from']);

2。使用打印代替回声

($shippingCost["ShippingCost"]['shipping_type'] == 'order_sum') ? 

print $this->Format->money($shippingCost["ShippingCost"]['value_from']) :    
print number_format($shippingCost["ShippingCost"]['value_from']);

【讨论】:

    【解决方案2】:

    三元运算符是通用的简写if 语句,它只是返回表达式的简写方式。在这种情况下,您可以只在表达式上使用三元,并从中提取 echo

    echo ($shippingCost["ShippingCost"]['shipping_type'] == 'order_sum') ?
          $this->Format->money($shippingCost["ShippingCost"]['value_from']) :
          number_format($shippingCost["ShippingCost"]['value_from']);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 2012-04-09
      • 1970-01-01
      • 2019-04-16
      • 2013-08-08
      • 1970-01-01
      • 2012-07-18
      相关资源
      最近更新 更多