Fonksiyonu php ile herhangi bir çıkış olup olmadığını öğrenin

3 Cevap php

Sizin için hızlı bir.

Ben bir dize verir bir işlevi var ki:

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

Nasıl işlev herhangi bir veri çıkışı olmadığını görmek için test hakkında gitmek istiyorsunuz?

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

3 Cevap

Çıktı tamponu fonksiyonlarını kullanarak:

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

Yani demek ...

function testa(){
  echo 'test';
}

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

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

Felix tarafından önerilen alternatif versiyonu:

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

Bir işlev veri döndürürse genellikle bir return statement bunu yapacaktır.

olarak

function myString() {

 $striing = 'hello';
 return $string;

}

Bunu test etmek için sadece işlevini çağırın ve döndürür ne olduğunu görmek.

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

Sen http://php.net/manual/en/function.ob-start.php de çok daha fazla bilgi bulabilirsiniz

Üzgünüm, ben soruyu yanlış anlamışım. Çıktı tamponu thephpdeveloper açıklanabilir olarak gitmek için bir yol olmalıdır.

--- DEĞİL İLGİLİ ---

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

Dönüş değeri olduğunda sadece 'Boş Function' yazacak.