Can anybody tell the internal procedure of the below expression?
<?php echo '2' . print(2) + 3; ?>
// outputs 521
print
is not a function, so the parentheses don't work as you think. It's taking the value of the expression (2) + 3
(5
) and outputs it. It returns 1
itself, which is concatenated to '2'
, which is then echo
ed.
print(2) + 3
will result in 5 (it is the same as print (2 + 3)
or print 2+3
. Since print is not actually a function in this case, the parentheses are mostly meaningless. One last thing to note is that the print
gets evaluated before the echo
.
The output so far is: 5
echo '2' . print
will result in 21 because print always returns 1
The output now is: '521'
Echo a concatenated string composed of:
The string '2' The result of the function print('2'), which will return true, which gets stringified to 1 The string '3'
Now, the order of operations is really funny here, that can't end up with 521 at all! Let's try a variant to figure out what's going wrong.
echo '2'.print(2) + 3; This yields 521
PHP is parsing that, then, as:
echo '2' . (print('2') + '3')) Bingo! The print on the left get evaluated first, printing '5', which leaves us
echo '1' . print('2') Then the left print gets evaluated, so we've now printed '52', leaving us with
echo '1' . '1' ; Success. 521.
I would highly suggest not echoing the result of a print, nor printing the results of an echo. Doing so is highly nonsensical to begin with.
First the addition of 2 and 3 is done which results in 5 and that is output.
Next print returns 1
always. That return value is concatenated with 2
to get 21
which is then echoed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With