PHP quiz #2 - echoJune 15, 2019
When people get into PHP development, the first thing they usually learn is the echo statement. Despite its elementary nature, I've found its handling of multiple arguments to be quite tricky.
What will this code output?
AnswerShow the answer
If you're like me, you've probably guessed "abac", and under any other circumstances you would have been right.
When calling a function, every argument is evaluated before entering the function body.
The catch is, echo is not a function. It's a language construct. It has special meaning for the interpreter, and as such, it works a little differently.
Instead of evaluating all the arguments eagerly, it evaluates them one by one.
To understand the rationale behind echo's strange behaviour, consider variable declarations.
PHP allows declaring multiple variables in a single statement. The two code snippets below have the exact same effect:
Although echo doesn't have much in common with variable declarations conceptually, it handles multiple arguments in a very similar way:
That is, passing multiple arguments to echo is essentially the same as writing separate, consecutive echo statements.
This post is part of a series based on a presentation I gave on March 20, 2019.