This post is part of a series based on a presentation I gave at Cheppers on March 20, 2019.
PHP quiz #2 - echo argumentsJune 15, 2019
Echo was the first PHP statement I learned. It went great: I printed 'Hello, World!' to the screen and quickly moved on to more challenging problems. If only everything in programming was this easy.
What will this code output?
AnswerShow the answer
Arguments are usually evaluated before they're passed to a function. This is called eager evaluation.
Echo works a little differently. The arguments are not evaluated eagerly (in which case the answer would be "abac"). They are evaluated one by one.
Calm down!! There is a reason for this. It's quite logical, actually.
Many programming languages allow multiple variable declarations in one line. It's considered a bad practice in all of them.
In PHP, variable declarations can be shortened the following way:
As you can see, using commas is essentially the same as writing consecutive statements. It is legal in PHP, albeit discouraged because of readability reasons.
Echo is not a function. It's a language construct, like 'public', 'global' and 'static'. It has special meaning for the interpreter.
Although it doesn't have much in common with variable declarations, it handles multiple arguments in a very similar way:
Passing multiple arguments to echo is the same as writing separate, consecutive echo statements.
In modern PHP applications echo statements are buried in the depths of template systems.
They might be rarely needed in one's day-to-day work, but they're still one of the most fundamental PHP statements. It's worth knowing how they work.
Alright! We've learned enough about language constructs for now. In the next post we'll take a look at operator associativity.