-1

我正在尝试在两者之间获取函数输出文本,如下所示。但它总是在顶部结束。知道如何正确设置吗?应该是 Apple Pie、Ball、Cat、Doll、Elephant,但 Doll 总是排在最前面。

function inBetween()
{
echo 'Doll <br>';
}

$testP = 'Apple Pie <br>';
$testP .='Ball <br>';
$testP .='Cat <br>';
inBetween();
$testP .='Elephant';

echo $testP;
4

3 回答 3

6

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

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;

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

于 2012-08-14T10:53:31.907 回答
0

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

于 2012-08-14T10:54:14.067 回答
0

那是因为你跑inbetween()在你前面echo $testP

尝试:

function inBetween()
{
return 'Doll <br>';
}

$testP = 'Apple Pie <br>';
$testP .='Ball <br>';
$testP .='Cat <br>';
$testP .=inBetween();
$testP .='Elephant';

echo $testP;
于 2012-08-14T10:55:08.953 回答