39

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 does output other things, is there a good method for doing this? Maybe messing with the output buffer?

hakre
  • 193,403
  • 52
  • 435
  • 836
Wilco
  • 32,754
  • 49
  • 128
  • 160

4 Answers4

75

Yes, messing with the Output Buffer is 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.

strager
  • 88,763
  • 26
  • 134
  • 176
Cody Caughlan
  • 32,456
  • 5
  • 63
  • 68
  • 1
    I'm curious, in this case, what would happen if you had already started an output buffer previously in your code? Would PHP start a new buffer for this function and then end only that buffer, or would it cause all of the previously buffered output to be cleaned as well? – Wally Lawless Apr 17 '09 at 19:04
  • 1
    Power-coder: PHP would start a new buffer, and the ob_end_clean() call would only end the most recent buffer. http://us.php.net/manual/en/function.ob-end-clean.php – Jay Oct 02 '09 at 06:19
  • thanks. I was reinveting the wheel by writing my own function which replaces ECHO, and disables based on some bool flag..and i found this. – DhruvPathak Mar 28 '11 at 06:42
12

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

Ray Hidayat
  • 16,055
  • 4
  • 37
  • 43
4

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
  function testFunc() {
    echo 'Testing';
    return true;
  }

    ob_start();
    $output = testFunc();
    ob_end_clean();

    echo $output;
?>
Dexygen
  • 12,287
  • 13
  • 80
  • 147
0

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.

Stephen Baugh
  • 673
  • 1
  • 9
  • 24
  • In the case of doing it for testing purposes, if the echoed statements aren't important then I would argue that it is better to use the output buffer. This way you can avoid unnecessary logic in your code. – unflores Jun 05 '13 at 16:36
  • yes, and I have used it, but it muddies up the code with testing constructs . . . – Dennis Dec 18 '14 at 16:10