I’ve came across an example in print manual of php.net. that stats.
echo 3 . print(2) . print(4) . 5 . 'c' .
print(6) . print(7). 'b' .print(8) . 'a';
which prints 8a7b16145c12131. But how?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I think you just got fooled by presence of concatenation operator
.which made you assume that the only output from this code would come fromechoand all other functions would only “contribute” to echo’s argument. It is wrong, of course, because you assumed thatprint()somehow changed its behaviour and returns its output there, instead of printing it out instantly (upon a call) to the output stream. The only thing you concatenate there are strings and eachprint()‘s ** return value**. And the latter, according to the manual is always “1”. Changeprint(), tosprintf()and all the “magic” will be gone.BTW it is good brainer – can keep busy for a while 🙂
EDIT ON OP’s REQUEST
The “culprit” here is
print. It is worth noting that it is not a real function but language construct which influences the way it is handled during evaluation. For example:produces:
But if you move
printinto function like this:then the output will look more sane:
If you care about details you will need to lurk into Zend Engine sources, but in general, such syntax is likely used for anything useful. Remembering
printis tricky suffices.And why we see “231c” anyway? It is because
echoarguments needs first to be evaluated – without that PHP do not really know what to echo (or could know partially). So PHP goes more/less this way:x(2)– since this function doesprint, our argument (“2”) will be instantly printed to the output. Function returns “1” becauseprintalways return “1” (see manual) so PHP concatenates “1” to so we now have “31”,echoour temporary string.Note that in fact
echooutputs ’31c’ only. Prefixing “2” is there because it isprintoutput and we had not used LF (or<br />if you are not testing this in console) in meantime so all output goes into one line. If you change the code to use LF (or<br />):then the output will be:
Hope this helps.