Find out if there is a function with php output

Quick for you guys.

Say I have a function that outputs a string:

function myString() { echo 'Hello World'; } 

How do I get tested to see if the function outputs any data?

 if(myString() ==''){ echo ''Empty function; } 
+1
function php
source share
3 answers

Using output buffer functions:

 function testFunctionOutput($f, $p = array()){ ob_start(); call_user_func_array($f, $p); $s = ob_get_contents(); ob_end_flush(); return (bool)($s !== ''); } 

So to speak...

 function testa(){ echo 'test'; } function testb($b){ $i = 20 * $b; return $i; } var_dump(testFunctionOutput('testa')); var_dump(testFunctionOutput('testb', array(10))); 

An alternative version suggested by Felix:

 function testFunctionOutput2($f, $p = array()){ ob_start(); call_user_func_array($f, $p); $l = ob_get_length(); ob_end_clean(); return (bool)($l > 0); } 
+8
source share

Normally, if a function returns data, it will do so in the return statement .

how in

 function myString() { $striing = 'hello'; return $string; } 

To verify this, simply call the function and see what it returns.

If you ask if something will be written for output, as indicated in CT below ... you will need to do something like this:

 //first turn out the output buffer so that things are written to a buffer ob_start(); //call function you want to test... output get put in buffer. mystring(); //put contents of buffer in a variable and test that variable $string = ob_get_contents(); //end output buffer ob_end() //test the string and do something... if (!empty($string)) { //or whatever you need here. echo 'outputs to output' } 

You can learn a lot more about http://php.net/manual/en/function.ob-start.php

+2
source share

Sorry, I misunderstood the question. The output BUffer should be a way, as thephpdeveloper explained.

--- DOES NOT MATCH ---

 if(!myString()){ echo 'Empty function'; } 

will echo 'Empty Function' when myString returns a value that can be evaluated in false IE: o, false, null, "", etc.

 if(myString() === NULL){ echo 'Empty function'; } 

Will print only "Empty Function" when there is no return value.

0
source share

All Articles