2011-01-14 79 views
3

可能重复:
How are echo and print different in PHP?PHP:使用echo而不是print有什么好处?

据我所知printecho之间的不同之处在于print返回一个布尔值。所以每当我用echo我可以用print代替。尽管如此,在我看到的所有代码示例中(我正在学习PHP),他们使用了echo。这是为什么?

编辑:也许原因是echoprint快(因为print返回一个值和echo没有)?尽管如此,我认为速度差异并不明显。

+0

因为`echo`没有返回值 – Mchl 2011-01-14 18:32:40

回答

6

print返回一个值,而echo不会使echo略快(不是什么大不了的)。你可以看看这个职位更多:

除此之外,您使用echooutput东西不像print得到一些返回值了。因此,echo得到最好的队列中,但没有什么可以阻止你使用print

alt text

+0

我不知道我们如何能给予信贷这样的测试。我相信它可以从版本更改为版本,并取决于配置,输出缓冲或其他因素。 – Savageman 2011-01-14 18:36:11

2

使用echoprint稍快,但对于大多数的目的,不应该的问题。

1

它不会改变任何东西。您可以使用其中一个或另一个。没有特别的用途返回1,每个人都按照惯例使用回声,也许这是历史性的。写起来也更快(4个字母而不是5个)。

3

This article已经探讨过这个问题,以更大的深度比你甚至可能已经知道是可能的。

来自:http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

1.

Speed. There is a difference between the two, but speed-wise it should be irrelevant which one you use. echo is marginally faster since it doesn't set a return value if you really want to get down to the nitty gritty. 

2.

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"; 

打印也是其它需要的,如果它是要内的使用的优先顺序表的一部分复杂的表达。它只是在优先级列表的底部。只有“,”AND,OR和XOR较低。

  1. 参数(一个或多个)。语法是:echo expression [,expression [,expression] ...]但是echo(expression,expression)无效。这将是有效的:echo(“howdy”),(“partner”);相同:echo“howdy”,“伙伴”; (把括号放在这个简单的例子中是没有用的,因为没有像这样的单个术语的运算符优先级问题。)

因此,回声不带括号可以采取多种参数,其中获得级联:

echo "and a ", 1, 2, 3; // comma-separated without parentheses 
    echo ("and a 123");  // just one parameter with parentheses 

打印()只能取一个参数:

print ("and a 123"); 
    print "and a 123"; 
1

大多数时候它只是归结为个人偏好。

echo但是可以有具有一个以上的参数和print返回一个值。

1

简短的回答你的问题是没有,也没关系,你使用。有一些细微的差异,但没什么可担心的。我将重点介绍一些在他们下面的:

  1. print可以在表达式中使用,而echo不能。例如,对于print,以下是可能的:($foo == true) ? print 'true' : $foo = true,但与echo替换会导致错误
  2. echo可以采取多个参数,以逗号分隔,而print不能。例如,你会做echo "hello", "world";
  3. print总是“返回”的价值1
相关问题