In PHP, why wasn't echo implemented as a function? (not echo vs. printf)
Asked Answered
N

3

7

I'm just curious. In PHP, why wasn't echo implemented as a function? Why didn't PHP just give us printf and never tell about echo? Please note that:

  • This is not a question about echo vs. printf.
  • I already knew that echo is a language construct.

UPDATE: By the way, was printf implemented using echo?

Neoplasticism answered 30/8, 2010 at 9:6 Comment(2)
Why does it seem that most people trying to answer or lock this haven't even read the question completely?Herra
(sourcecode) HEAD revision of formatted_print.cMuchness
R
1

Echo is a language construct. Function use language construct to do their job. Explaining is not exactly my specialty, but a google action brought me to this topic:

What is the difference between a language construct and a "built-in" function in PHP?

Some important content:

...

This is the root of why you can't redefine language constructs like echo or print: they're effectively hardcoded into the parser, whereas functions are mapped to a set of language constructs and the parser allows you to change that mapping at compile- or runtime to substitute your own set of language constructs or expressions.

...

Rhetorical answered 30/8, 2010 at 9:17 Comment(2)
Thanks. I've read that before. But I'm just curious why PHP team exposed echo, a language construct that I rarely see in other programming language, instead of wrapping it in a function (IIRC, Python changed print to function in version 3).Neoplasticism
@Hai Minh Nguyen: Well, I don't think that Rasmus Lerdorf, Zeev Suraski, or Andi Gutmans are here at SO. I think that as the initial creators of PHP, only they could give a satisfactory answer to the reason for this behavior. (They probably had one, but it is hidden in the mists of time from us, mere mortals ;))Loupgarou
N
1

Echo is not a function and it doesn't return a value like print. Print is a language construct too - does not require parenthesis.

Manual: echo - No value is returned. print - Returns 1, always.

The fact remains that returning a value degrades system performance.

So.. now since printf IS a function (which returns the length of the outputted string) the answer I believe is obvious.

Nutting answered 30/8, 2010 at 9:25 Comment(1)
Also you can use: echo $var1, $var2, $var3; This avoids concatenation.Nutting
H
-1

Just a wild guess, but perhaps it's because PHP used to exist as CGI binaries. So it would be for making porting shell scripts easier, since you could use the echo binary in those.

Herra answered 30/8, 2010 at 9:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.