2011-01-14 46 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
相關問題