这些三元运算符输出相同的结果吗?

时间:2014-05-20 18:41:46

标签: php operator-keyword ternary

$time ?: 3600是否等同于isset($time) ? $time : 3600

谢谢大家。

2 个答案:

答案 0 :(得分:2)

没有。在某些情况下,他们会评估相同的值,但它们并不等同。

<?php
print $time ?: 3600;
print "\n";
print isset($time) ? $time : 3600;
print "\n\n";

$time = 0;
print $time ?: 3600;
print "\n";
print isset($time) ? $time : 3600;
print "\n\n";

$time = 30;
print $time ?: 3600;
print "\n";
print isset($time) ? $time : 3600;
print "\n\n";
?>

输出:

PHP Notice:  Undefined variable: time in /home/hq6/PHP/Test2.php on line 2
3600
3600

3600
0

30
30

答案 1 :(得分:1)

不,不完全。 $time ?: 3600与执行$time ? $time : 3600类似。

区别在于$time0isset($time)将返回TRUE,因此,您获得$time0),而如果第一个$time0你得到3600