获取函数输出介于两者之间的文本


Getting a functions output text in between

我正在尝试在两者之间获取函数输出文本,如下所示。但它总是以顶级告终。知道如何设置它吗?它应该是苹果派、球、猫、娃娃、大象,但娃娃总是在顶部结束。

function inBetween()
{
echo 'Doll <br>';
}
$testP = 'Apple Pie <br>';
$testP .='Ball <br>';
$testP .='Cat <br>';
inBetween();
$testP .='Elephant';
echo $testP;

该函数在屏幕顶部回显,因为它首先运行。您正在追加到字符串,但直到函数运行后才显示它 - 它首先输出回显。尝试如下返回值:

function inBetween()
{
    return 'Doll <br>';
}
$testP = 'Apple Pie <br>';
$testP .='Ball <br>';
$testP .='Cat <br>';
$testP .= inBetween();
$testP .='Elephant';
echo $testP;

编辑:您也可以通过引用传递,其工作原理如下:

function inBetween(&$input)
{
    $input.= 'Doll <br>';
}
$testP = 'Apple Pie <br>';
$testP .='Ball <br>';
$testP .='Cat <br>';
inBetween($testP);
$testP .='Elephant';
echo $testP;

变量传递给函数会向其发送副本时,使用函数声明中的&将变量本身发送给它。函数所做的任何更改都将成为原始变量。这意味着函数附加到变量,整个东西在最后输出。

那是因为你在echo $testP之前运行inbetween()

尝试:

function inBetween()
{
return 'Doll <br>';
}
$testP = 'Apple Pie <br>';
$testP .='Ball <br>';
$testP .='Cat <br>';
$testP .=inBetween();
$testP .='Elephant';
echo $testP;

而不是 echo 使用 return 'Doll <br>'; 然后$testP .= inBetween();