簡體   English   中英

在PHP中,是否可以將函數放入變量,然后先將字符串放入變量中打印?

[英]in PHP, is it possible to put function into a variable and let the string into the the variable print first?

我有一個問題:(我已經在Google上搜索了它,但找不到任何答案)。 變量中的字符串是否有可能首先運行? 例如 :

   <?php

function example($times) { 
for($i = 4; $i < $times; $i++)   echo $i; 
}
$var = example(10);
echo  "3$var";

?>

和此代碼打印:

4567893

將結果收集為函數內部的變量並返回。

<?php

function example($times) { 
  $result='';
  for($i=4;$i<$times;$i++) $result.=$i; 
  return $result;
}
$var=example(10);
echo "$var"."3";

換句話說, 只有在您無法控制函數的輸出或它具有許多html標記的情況下使用輸出緩沖區捕獲:

<?php

function example($times) { 
  for($i=4;$i<$times;$i++) echo $i;
}

ob_start();
example(10);
$var=ob_get_clean;
echo "$var".3;

php.net上的更多信息

嘗試:

function example($times) { 
 $str='';
 for($i = 4; $i < $times; $i++)   
  $str .=$i; 
 return $str;
}

$var = example(10);   
echo  $var."3";

您需要了解echoreturn之間的區別。

您的函數example將直接回顯輸出。 $var值為NULL ,不顯示任何內容。

因此,您實際上正在執行以下操作:

echo 4; // in example()
echo 5; // in example()
echo 6; // in example()
echo 7; // in example()
echo 8; // in example()
echo 9; // in example()
echo "3"; // $var == '';

如果要收集輸出,請編寫如下example

function example($times) {
    $numberstring = '';
    for($i = 4; $i < $times; $i++) {
        $numberstring .= $i; 
    }
    return $numberstring;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM