代码之家  ›  专栏  ›  技术社区  ›  Keith Donegan

找出函数是否有php输出

  •  1
  • Keith Donegan  · 技术社区  · 16 年前

    给你们快点。

    假设我有一个输出字符串的函数:

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

    我该如何测试函数是否输出任何数据?

    if(myString() ==''){ 
          echo ''Empty function;  
    }
    
    3 回复  |  直到 16 年前
        1
  •  8
  •   mauris    16 年前

    使用输出缓冲区函数:

    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)));
    

    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);
    }
    
        2
  •  2
  •   dkinzer    16 年前

    通常,如果函数返回数据,它将在 返回语句 .

    如在

    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

        3
  •  0
  •   Javier Parra    16 年前

    对不起,我误解了这个问题。输出缓冲区应该是hpdeveloper所解释的方法。

    ---不相关---

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

    当mystring返回可计算为false的值时,将回显“empty function”: o,假,空,“……

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

    只有在没有返回值时才会打印“空函数”。

    推荐文章