Find out if function has any output with php
Quick one for you guys.
Say I have a function that outputs a string:
function myString()
{
echo 'Hello World';
}
How would I go about testing to see if th开发者_StackOverflowe function outputs any data?
if(myString() ==''){
echo ''Empty function;
}
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 say...
function testa(){
echo 'test';
}
function testb($b){
$i = 20 * $b;
return $i;
}
var_dump(testFunctionOutput('testa'));
var_dump(testFunctionOutput('testb', array(10)));
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);
}
Usually if a function returns data it will do so in a return statement.
as in
function myString() {
$striing = 'hello';
return $string;
}
To test it just call the function and see what it returns.
If what you are asking is if something will be written to output as CT commented 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 find out a lot more at http://php.net/manual/en/function.ob-start.php
Sorry, I misunderstood the question. Output BUffer should be the way to go as explained by thephpdeveloper.
---NOT RELEVANT---
if(!myString()){
echo 'Empty function';
}
will echo 'Empty Function' when myString returns a value that can be evaluated to false IE: o, false, null, "" etc...
if(myString() === NULL){
echo 'Empty function';
}
Will only print 'Empty Function' when there is no return value.
精彩评论