Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I know the above code outputs 323

But need an explanation on how is it outputting 323

Anybody can pls explain?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
136 views
Welcome To Ask or Share your Answers For Others

1 Answer

Both echo and print are intended to behave more like language constructs and not functions. As such they have a flow of control. What happens here in your code is that you are calling print from inside of a language construct (echo). Meaning that print will send its output first before echo has completed its task (remember you called print from inside of echo).

To show you what's happening a bit more clearly, it actually has nothing to do with operator precedence at all.

echo ('a') . ('b' * (print 'c')); // ca0

// This is the same thing as...

echo 'a' . 'b' * print 'c';       // ca0

Notice the operators have no effect on the order of the characters in the resulting output here.

print always returns 1 so what happens here is that you performed an arithmetic operation on 'b' * 1, which is the stirng b multiplied by the return value of print. Thus why you see the output as c (print sent output before echo has even finished doing it's job), first, and then everything that echo was supposed to print.

Let me elaborate even further with the following example...

echo print 'a' . 'b' . 'c'; // abc1

Notice the 1 at the end of that output. This is because all echo did was output the return value of print and not the string. Instead, print is the one that provided the abc as output (and remember print is able to send output before echo can since echo has to wait to process everything inside of the construct before it can finish).

This makes it even more clear...

echo (print 'a') . 'b' . 'c'; // a1bc

Now the 1 comes right after a.

If you want echo to send the output for each expression individually, you can supply one argument for every expression you want processed and sent to output... So for example:

echo print 'a', 'b', 'c'; // a1bc
echo 2, 3 * print 3; // 233

I hope that clarifies it a bit more for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...