Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "print" prints from right to left?

Tags:

php

Can anyone please explain to me how this works:

<?php
    print 5 . print 6 . print 7;
?>

it prints: 76151

I know the 1 is the return value from the print function, but why are the functions called in reverse order?

like image 686
MilMike Avatar asked Jul 18 '12 14:07

MilMike


2 Answers

I believe this occurs because the dot operator is left-associative.

The expression would look like this with parenthesis:

print 5 . (print 6 . (print 7));
like image 180
nickb Avatar answered Sep 23 '22 21:09

nickb


Your function is evaluating from right to left.

The trace is similar to this:

print (5 . print 6 . print 7)

print 7 evaluates first, printing 7 and returning 1.

print (5 . print 6 . 1)

This traces to print 61 and returning 1 Lastly:

print (5 . 1)

And thus you have 76151.

like image 27
Daniel Li Avatar answered Sep 22 '22 21:09

Daniel Li