如何将函数调用的 echo 语句分配给变量?

How to assign the echo statement from a function call to a variable?

我正在尝试获取函数的回显并将值添加到变量中。

这就是我所做的。

function myfunction() {
   echo 'myvar';
}

然后我想把它变成这样的变量:

$myVariable = myfunction();

我认为这会起作用,但我没有起作用。

这不是方法吗?如果没有,我该怎么做?

您可以调用该函数,同时您已打开 output buffering,然后您可以捕获输出。例如

<?php

    ob_start();
    myfunction();
    $variable = ob_get_contents();
    ob_end_clean();

    echo $variable;

?>

输出:

myvar

或者您只需将 echo 语句更改为 return 语句。


您当前的版本不起作用,因为您没有 return 函数中的值。由于您省略了 return 语句,因此值 NULL 得到 returned 并分配给您的变量。你可以通过这样做看到这一点:

$variable = myfunction();
var_dump($variable);

输出:

NULL