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

Categories

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

printing - Strange echo, print behaviour in PHP?

The following code outputs 43211, why?

  echo print('3').'2'.print('4');
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Your statement parses to humans as follows.

Echo a concatenated string composed of:

  1. The result of the function print('3'), which will return true, which gets stringified to 1
  2. The string '2'
  3. The result of the function print('4'), which will return true, which gets stringified to 1

Now, the order of operations is really funny here, that can't end up with 43211 at all! Let's try a variant to figure out what's going wrong.

echo '1' . print('2') . '3' . print('4') . '5';

This yields 4523111

PHP is parsing that, then, as:

echo '1' . (print('2' . '3')) . (print('4' . '5'));

Bingo! The print on the left get evaluated first, printing '45', which leaves us

echo '1' . (print('2' . '3')) . '1';

Then the left print gets evaluated, so we've now printed '4523', leaving us with

echo '1' . '1' . '1';

Success. 4523111.

Let's break down your statement of weirdness.

echo print('3') . '2' . print('4');

This will print the '4' first, leaving us with

echo print('3' . '2' . '1');

Then the next print statement is evaluated, which means we've now printed '4321', leaving us with

echo '1';

Thus, 43211.

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.


Upon further review, I'm actually not entirely sure how PHP is parsing either of these bits of nonsense. I'm not going to think about it any further, it hurts my brain.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...