为什么三元运算符在 php 中与 print 一起使用而不与 echo 一起使用?
Why does the ternary operator work with print but not with echo in php?
这个有效:
$number = 1;
$number == 1? print 'yes' : print 'no';
但这不起作用:
$number = 1;
$number == 1? echo 'yes' : echo 'no';
为什么 PHP 会发生这种情况?
检查您的日志是否有警告。三元运算符 必须 return 一个值。 print
returns 1
总是,但 echo
没有 return 值。
关于您关于将 echo
放入函数的评论,默认情况下没有明确 return 值 return null
的函数,因此,该函数是确实 returning 一个值:
http://php.net/manual/en/functions.returning-values.php
http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
三元运算符的参数必须是表达式。 print 'yes'
是表达式,echo 'yes'
不是,因为echo
是特殊语法。
使用三元运算符作为 echo
的参数,而不是相反。
echo $number == 1 ? 'yes' : 'no';
这和你不会写的原因是一样的:
$var = echo 'yes';
这个有效:
$number = 1;
$number == 1? print 'yes' : print 'no';
但这不起作用:
$number = 1;
$number == 1? echo 'yes' : echo 'no';
为什么 PHP 会发生这种情况?
检查您的日志是否有警告。三元运算符 必须 return 一个值。 print
returns 1
总是,但 echo
没有 return 值。
关于您关于将 echo
放入函数的评论,默认情况下没有明确 return 值 return null
的函数,因此,该函数是确实 returning 一个值:
http://php.net/manual/en/functions.returning-values.php
http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
三元运算符的参数必须是表达式。 print 'yes'
是表达式,echo 'yes'
不是,因为echo
是特殊语法。
使用三元运算符作为 echo
的参数,而不是相反。
echo $number == 1 ? 'yes' : 'no';
这和你不会写的原因是一样的:
$var = echo 'yes';