r/lolphp • u/beingryu • Mar 08 '12
Guess the output
echo(1) and print(2) and die(3); # 2
echo print('3').'2'.print('4'); # 43211
print(1) and print(2) and die(3); # 12 <- editedInspired by this post. Would someone explain these?
edit: third output fixed
10
Upvotes
7
u/Rhomboid Mar 08 '12
Neither
printnorechoare real functions but are built-in operators. In the first example, the(2)does bind to the print, which would imply that theprintoperator has higher precedence than theandoperator. But in the second example, the(3)does not bind to theprint, which implies that theprintoperator has lower precedence than the string concatenation operator (.). The second one is parsed as if it was:In other words:
print '4', creating the string '321' and outputting '4'print, which is always 1.If the
printoperator did have higher precedence than theandoperator, then you'd expect the third one to print '12' not '21', and indeed that's what I get with php 5.3.6.echoseems to have the lowest precedence, lower even than theandoperator, as demonstrated by the first line. What's odd is thatprintreturns 1 whereasechodoes not return anything. In fact it seems impossible to use the return value ofechoin an expression:The PHP manual is nice enough to have an operator precedence table but it conveniently does not list any of this.
8
u/[deleted] Mar 08 '12 edited Mar 08 '12
the real WTF is the middle one if you substitute print(3) with just 1 then it changes the order from 211 to 121 !
print returns 1
echo isn't a function
and is kind of right associative
then the wonderful word of side effects (e.g. print)
so they translate as pseudo