[php]echo vs print

カテゴリ: php / author: uechoco / 2007年11月02日 21:55:28
この記事を読む時間:534くらい

 phpで単純な文字列を出力するとき、echoprintのどちらを使用していますか?私はecho構文です。

 echoもprintも言語構造なので関数よりは早く処理してくれそうな気がします。また括弧でくくる必要がないのも共通です。私がechoを使用しているのは、printより1文字短いだけです。

 ただ、改めてマニュアルを見ると、echoとprintの比較議論のページ(英語)のリンクがちゃんと貼ってあるんですね。

There is a difference between the two, but speed-wise it should be
irrelevant which one you use. print() behaves like a function in that
you can do: $ret = print “Hello World”;And $ret will be 1That means
that print can be used as part of a more complex expression where echo
cannot. print is also part of the precedence table which it needs to
be if it is to be used within a complex expression. It is just about at
the bottom of the precendence list though. Only “,” AND, OR and XOR
are lower.echo is marginally faster since it doesn’t set a return value
if you really want to get down to the nitty gritty.If the grammar is:
echo expression [, expression[, expression] … ]Then echo (
expression, expression ) is not valid. ( expression ) reduces to just
an expression so this would be valid: echo (“howdy”),(“partner”);but
you would simply write this as: echo “howdy”,”partner”; if you wanted
to use two expression. Putting the brackets in there serves no purpose
since there is no operator precendence issue with a single expression
like that.(http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40)

 相変わらず英語なので適当に読んでいます。しかもこの英語がごちゃごちゃしていて嫌いです。以下に勝手に訳しましたが参考程度にお願いします。ぁ、斜体の英文は私の英語力ではうまく訳せないorよくわからないところです。

echo構造とprint構造には違いがありますが、速さの観点から言えばどちらを使っても変わりないです。print構造は関数のような振る舞いをします。例えば「$ret = print “Hello World”;」のように書けます。このとき、返り値の$retは 1 でしょう。このことは、print構造が、echo構造が使えないようなもっと複雑な構文の中に使うことができることを意味しています。It is just about at the bottom of the precendence list though. Only “,” AND, OR and XOR are lower. echo構造は、核心的なことを言うのであれば、返り値をセットしないので、わずかにprintよりも早いです。文法は次のようになります「echo expression [, expression[, expression] … ]」。このとき「echo (expression, expression )」では動きません。もし、2つの式をecho構造で使いたいのであれば、( expression ) reduces to just an expression so this would be valid: 「echo (“howdy”),(“partner”);」。しかし、もっと簡単に書くとしたら、「echo “howdy”,”partner”;」と書きます。括弧をつける意味はありません。というのは、先ほどのような単項式には演算子の優先順位の問題は発生しないからです。

 私はprint構造が関数のように振舞ったところで、関数のように使わないので、恩恵を受けられそうにありません。それよりかは、カンマで式を増やすことのできるecho構造の方が、私向きです。


コメントはまだありません »

コメントはまだありません。

この投稿へのコメントの RSS フィード。 TrackBack URI

コメントする

Copyright © 2012 うえちょこ@ぼろぐ. WP Theme created by Web Top.