Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

php - Explain the output of : echo (2) . (3 * (print 3));

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...