奇怪的回声,PHP 中的打印行为?

2021-12-28 00:00:00 printing php echo

下面的代码输出43211,为什么?

The following code outputs 43211, why?

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

推荐答案

您的语句将解析为人类,如下所示.

Your statement parses to humans as follows.

回显由以下组成的连接字符串:

Echo a concatenated string composed of:

  1. 函数print('3')的结果,返回true,字符串化为1
  2. 字符串'2'
  3. 函数print('4')的结果,返回true,字符串化为1
  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

现在,这里的操作顺序真的很有趣,根本不能以43211结尾!让我们尝试一个变体来找出问题所在.

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';

这产生 4523111

PHP 将其解析为:

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

宾果游戏!左边的 print 首先被评估,打印 '45',这给我们留下了

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

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

然后左边的 print 被计算,所以我们现在打印了 '4523',剩下

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

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

成功.4523111.

让我们分解一下你对怪异的陈述.

Let's break down your statement of weirdness.

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

这将首先打印 '4',留给我们

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

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

然后计算下一个打印语句,这意味着我们现在已经打印了'4321',剩下

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

echo '1';

因此,43211.

我强烈建议不要回显print的结果,也不要print的结果回声.这样做是非常荒谬的.

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.

经过进一步审查,我实际上并不完全确定 PHP 如何解析这些废话中的任何一个.我不会再去想它了,它会伤到我的大脑.

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.

相关文章