简写 if 语句有错误
Shorthanded if statement have errors
我想 shorthand 跟随 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']);
}
?>
我的 shorthanded 版本
<?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
没有任何 return 类型。这就是为什么你应该在开头使用 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。使用 print 而不是 echo
($shippingCost["ShippingCost"]['shipping_type'] == 'order_sum') ?
print $this->Format->money($shippingCost["ShippingCost"]['value_from']) :
print number_format($shippingCost["ShippingCost"]['value_from']);
三元运算符是通用的简写if
语句,它只是return表达式的简写方式。在这种情况下,您可以仅在表达式上使用三元组,并从中提取 echo
:
echo ($shippingCost["ShippingCost"]['shipping_type'] == 'order_sum') ?
$this->Format->money($shippingCost["ShippingCost"]['value_from']) :
number_format($shippingCost["ShippingCost"]['value_from']);
我想 shorthand 跟随 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']);
}
?>
我的 shorthanded 版本
<?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
没有任何 return 类型。这就是为什么你应该在开头使用 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。使用 print 而不是 echo
($shippingCost["ShippingCost"]['shipping_type'] == 'order_sum') ?
print $this->Format->money($shippingCost["ShippingCost"]['value_from']) :
print number_format($shippingCost["ShippingCost"]['value_from']);
三元运算符是通用的简写if
语句,它只是return表达式的简写方式。在这种情况下,您可以仅在表达式上使用三元组,并从中提取 echo
:
echo ($shippingCost["ShippingCost"]['shipping_type'] == 'order_sum') ?
$this->Format->money($shippingCost["ShippingCost"]['value_from']) :
number_format($shippingCost["ShippingCost"]['value_from']);