【问题标题】:How to avoid echo when calling the function and want only the return value in PHP调用函数时如何避免回显并且只需要PHP中的返回值
【发布时间】:2021-03-27 21:07:12
【问题描述】:

我在其中返回值的函数,但当我调用此函数时,它也会回显另一个函数。

function myFunction(){
       $output1 = anotherFunc();
       $output2 = " Hello World!";
       return $output2;
    }
    function anotherFunc(){
        echo "Hey this is paragraph";
    }
    
    $data = myFunction();
    print_r($data);

【问题讨论】:

  • 您可以将代码中的echo 更改为return 吗?
  • 要么改变回声以返回 Magnus Eriksson 提到的,要么你 save the output to a variable
  • Magnus Eriksson,这只是示例。我无法访问另一个 Func,这就是我苦苦挣扎的原因。
  • 请注意$output1 = anotherFunc();null 填充$output1,因为anotherFunc() 不返回任何内容。您是否需要实际获取回显的字符串?

标签: php


【解决方案1】:
<?php
function myFunction(){
    ob_start();
    $output1 = anotherFunc();
    ob_end_clean();
    $output2 = " Hello World! $output1";

    return $output2;
}

function anotherFunc(){
    echo "Hey this is paragraph";
    return 5;
}
echo myFunction();

ob_start - 此函数将打开输出缓冲。当输出缓冲处于活动状态时,脚本不会发送任何输出(标题除外),而是将输出存储在内部缓冲区中。

ob_end_clean - 此函数丢弃最顶层输出缓冲区的内容并关闭此输出缓冲。如果要进一步处理缓冲区的内容,则必须在 ob_end_clean() 之前调用 ob_get_contents(),因为调用 ob_end_clean() 时会丢弃缓冲区内容。

【讨论】:

  • 谢谢,离我很近。我会相应地更新我的代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多