PHP:抑制函数内的输出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/486181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: Suppress output within a function?
提问by Wilco
What is the simplest way to suppress any output a function might produce? Say I have this:
抑制函数可能产生的任何输出的最简单方法是什么?说我有这个:
function testFunc() {
echo 'Testing';
return true;
}
And I want to call testFunc() and get its return value without "Testing" showing up in the page. Assuming this would be in the context of other code that doesoutput other things, is there a good method for doing this? Maybe messing with the output buffer?
我想调用 testFunc() 并获取其返回值,而不会在页面中显示“测试”。假设这是在其他代码的情况下不输出其他的东西,是有这样的好方法?也许弄乱了输出缓冲区?
回答by Cody Caughlan
Yes, messing with the Output Bufferis exactly the answer. Just turn it on before you call your method that would output (not the function itself, but where you call it, you could wrap it around your whole script or the script flow, but you can make it as "tight" as possible by just wrapping it around the call of the method):
是的,搞乱输出缓冲区正是答案。只需在调用将输出的方法之前打开它(不是函数本身,而是在调用它的地方,您可以将它包装在整个脚本或脚本流中,但您可以通过以下方式使其尽可能“紧密”将它包裹在方法的调用中):
function foo() {
echo "Flush!";
return true;
}
ob_start();
$a = foo();
ob_end_clean();
And no output is generated.
并且不产生任何输出。
回答by Ray Hidayat
Here you go:
干得好:
ob_start();
testFunc();
ob_end_clean();
"ob" stands for "output buffering", take a look at the manual pages here: http://www.php.net/outcontrol
“ob”代表“输出缓冲”,看看这里的手册页:http: //www.php.net/outcontrol
回答by Dexygen
Yes you are on the right track as to leveraging PHP's output buffering functions, i.e. ob_start and ob_end_clean (look them up on php.net):
是的,您在利用 PHP 的输出缓冲函数方面走在正确的轨道上,即 ob_start 和 ob_end_clean(在 php.net 上查找它们):
<?php
function testFunc() {
echo 'Testing';
return true;
}
ob_start();
$output = testFunc();
ob_end_clean();
echo $output;
?>
回答by Stephen Baugh
Isn't it as easy as applying some conditions to your code?
是不是像在代码中应用一些条件一样简单?
I mean if variable = testing then output, else don't?
我的意思是如果变量 = 测试然后输出,否则不?
For functions that have a result that outputs direct to the browser like EVAL, you could capture the result in an ob_start.
对于具有直接输出到浏览器(如 EVAL)的结果的函数,您可以在 ob_start 中捕获结果。

