当在函数中使用'echo'时,为什么结果出现在前一行? [英] when using 'echo' in function, why does result appear on previous line?

查看:81
本文介绍了当在函数中使用'echo'时,为什么结果出现在前一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



当我在调用函数的页面中写入时 -

p>

  echo< br /> getalbumartistfunction:.get_albumartistid($ thisalbum); 

它返回上面的行上的artist_id数字,我拥有该函数呼叫。
所以我进入函数并将它从'echo'切换到'return',现在它就像我期望的那样出现在冒号后面(并且可能更符合我需要的内容)。



所以它可以工作。但是我非常困惑,为什么当函数设置为回显它时,它会在前一行显示结果。

当函数被调用时,get_albumartistid中的echo会立即执行,而echo... ...会在返回之前组合该字符串 - 实质上是在回声之前缓冲整个事件。返回而不是回声是处理这种情况的正确方法,因为这将有效地用返回的字符串替换函数调用。如果您要使用echo,您必须:

  echo< br /> getalbumartistfunction:; 
get_albumartistid($ thisalbum);

有效地变成:

  echo< br /> getalbumartistfunction:; 
echo<艺术家ID>;

在您的原始示例中,执行顺序使其成为:

  echo<艺术家ID>; 
echo< br /> getalbumartistfunction:;

由于所有回声在被调用时立即发生,并且PHP没有缓冲您的外部回声语句。 p>

I wrote up a function that echoed out the id at the otherside of a linked table.

when I write in the page that's calling the function--

echo "<br/>getalbumartistfunction: ".get_albumartistid($thisalbum);

it returns the artist_id number on the line above where I have that function call. So I went into the function and switched it from 'echo' to 'return' and it now appears right after the colons like I would expect (and is probably more along the lines of what I need).

So it works. But I am extremely confused why it would show the result on the previous line when the function is set to echo it.

解决方案

The echo in the get_albumartistid is executed immediately when the function is called while the echo "
..." assembles the string before echoing it - essentially buffering the entire thing before it echoes. Return instead of echo is the proper way to handle this since that would effectively replace the function call with the string returned. If you were to use echo you'd have to:

echo "<br/>getalbumartistfunction: ";
get_albumartistid($thisalbum);

Which effectively becomes:

echo "<br/>getalbumartistfunction: ";
echo "<The artist id>";

In your original example that order of execution makes it:

echo "<The artist id>";
echo "<br/>getalbumartistfunction: ";

Since all echoes happen immediately when it's called and PHP is not done buffering your outer echo statement.

这篇关于当在函数中使用'echo'时,为什么结果出现在前一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆