2010-04-14 43 views

回答

8

使用输出缓冲功能:

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

所以说......

function testa(){ 
    echo 'test'; 
} 

function testb($b){ 
    $i = 20 * $b; 
    return $i; 
} 

var_dump(testFunctionOutput('testa')); 
var_dump(testFunctionOutput('testb', array(10))); 

替代版本由费利克斯·建议:

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

+1但是为了只测试一个函数是否产生输出,'ob_end_clean'比'ob_end_flush'更适合。除了'ob_get_contents','ob_get_length'也可以使用。 – 2010-04-14 16:57:29

+0

感谢球员们,但得到一个“警告:缺少论点1”错误 – 2010-04-14 17:06:34

+0

没有函数echo输出,而是返回它。这样你就可以更灵活地做这样的事情。所以当你只是想显示它说print myFunction(); – TravisO 2010-04-14 17:09:19

0

对不起,我误解了这个问题。输出BUffer应该是像php开发者所解释的那样。

--- NOT RELEVANT ---当myString的返回可被评估为假IE的值

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

将回声 '空函数': O,假,空 “” 等。

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

只有当没有返回值时才会打印'Empty Function'。

+0

这是检查返回值的好方法,但我不认为这回答了OP的要求。我认为OP想知道是否有办法确定函数是否写入输出流。 – 2010-04-14 16:54:44

2

通常,如果一个函数返回的数据会做所以在返回语句

function myString() { 

$striing = 'hello'; 
return $string; 

} 

为了测试它只是调用函数,看看它返回。

如果你问是如果事情会被写入到输出CT如下评论...你需要做这样的事情:

//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' 
} 

你可以找到很多更在http://php.net/manual/en/function.ob-start.php

+0

我不认为这是什么OP是问,看到我的其他评论 – 2010-04-14 16:57:30

+0

好点,CT,我编辑了建议包括这种情况。 – dkinzer 2010-04-14 17:24:55