PHP quiz #2 - echo
June 15, 2019When 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.
Question
What will this code output?
-
A
bac a
-
B
baac
-
C
abac
-
D
abc a
Answer
Show the answerbaac
Explanation
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.
Variable declarations
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.