php - 为什么 print 和 echo 在 "for"循环中表现不同

标签 php for-loop printing echo behavior

<分区>

如果我在这段代码中使用print:

<?php
for($i = 1; $i <= 3; print $i . "\n") {
  $i++; 
}   
?>

我看到这样的输出:

2

3

4

但是当我使用 echo 时代码不起作用:

<?php
for($i = 1; $i <= 3; echo $i . "\n") {
  $i++; 
}   
?>

我看到这个错误:

PHP Parse error: syntax error, unexpected 'echo' (T_ECHO), expecting ')' in /media/datos/xampp/htdocs/temp/1.php on line 3

我的问题是:

  • 为什么我可以将 print 用作 for 循环中的第三个表达式,但在使用 echo 时却不能,为什么它们的行为与彼此?

引用资料:

最佳答案

Expression. print() behaves like a function in that you can do: $ret = print "Hello World"; And $ret will be 1. That means that print can be used as part of a more complex expression where echo cannot. An example from the PHP Manual:

$b ? print "true" : print "false";

我的部分回答是以下回答的一部分。我想这就是你问题的答案。最重要的部分是 print() 表现得像一个函数

查看此答案:https://stackoverflow.com/a/234255/1848929

echo 怎么样:

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

请参阅本页注释部分:http://us2.php.net/manual/en/function.echo.php

关于php - 为什么 print 和 echo 在 "for"循环中表现不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30715633/

相关文章:

c++ - for 循环在 if 条件下

r - 如何使用条件标签在循环中制作多个ggplots

printing - 打印特定区域(组件)

java - 在 java 中打印 HTML 文件

php - Yii 中的动态渲染

php - Netbeans将 “function print()”标记为语法错误

for-loop - Gnuplot 5.0补丁lvl1在WIN 8.1上崩溃

python - 为什么 Python 的 print 函数会这样?

php - 我希望有人能给我关于解决此问题的最佳方法的建议?

PHP 请求 : worker fails with "MySQL server has gone away"