2016-05-13 76 views
0

我有一個函數,並希望在完成時收集它的輸出日誌到電子郵件。它看起來是這樣的:從內部函數追加字符串到父變量

function blabla() { 
    $emailMessage = "some text"; 

    $emailMessage .= "some more text"; 

    function foo() { 
    for ($x = 1; $x <= 20; $x++) { 
     $emailMessage .= 'Call #' . $x; 
     // then doing an API call 
     return $response; 
    } 
    } 

    $res = foo(); 

    $emailMessage .= "last line of text"; 

} 

現在$emailMessage看起來是這樣的:some text || some more text || last line of text。來自內部函數的文本不被附加。

我怎樣才能得到它看起來像這樣:some text || some more text || call #1 || call #2 ||... || last line of text

------編輯------

感謝@kamal朋友我用一個全局變量。結果如下所示:

function blabla() { 
     global $emailMessage; 
     $emailMessage = "some text"; 

     $emailMessage .= "some more text"; 

     function foo() { 
     global $emailMessage; 
     for ($x = 1; $x <= 20; $x++) { 
      $emailMessage .= 'Call #' . $x; 
      // then doing an API call 
      return $response; 
     } 
     } 

     $res = foo(); 

     $emailMessage .= "last line of text"; 

    } 
+0

爲什麼要使用「內部函數」? – zoubida13

回答

1

這是由於範圍,兒童函數有它自己的範圍:

$emailResult .= 'Call #' . $x; 

應替換。

我能想到的兩個選項完成此任務:

  • 使用全局變量
  • 傳遞爲參考參數(見下面的例子)

function blabla() { 
    $emailMessage = "some text".PHP_EOL; 
    $emailMessage .= "some more text".PHP_EOL; 

    function foo(&$emailMessage) { // passed as ref argument 
    for ($x = 1; $x <= 20; $x++) { 
      $emailMessage .= 'Call #' . $x.PHP_EOL; 
      // then doing an API call 
      //return $response; //it will exit function 
    } 
    } 

    $res = foo($emailMessage); 

    $emailMessage .= "last line of text".PHP_EOL; 
    return $emailMessage; 

} 
echo blabla(); 

演示: https://eval.in/571036

+0

啊OK謝謝。所以我去了一個全球變種。我習慣於JavaScript範圍 - 這就是爲什麼我認爲全球不會是必要的;-) – Seb

0

您使用完全不同的變量名嗎?

$emailMessage .= 'Call #' . $x; 
+0

對不起,只是在這個例子!我編輯它... – Seb

0

更清晰的正確的(外部)函數

function blabla() { 
    $emailMessage = "some text"; 

    $emailMessage .= "some more text"; 

    $emailMessage = foo($emailMessage); 
    $emailMessage .= "last line of text"; 

} 


function foo($emailMessage) { 
    for ($x = 1; $x <= 20; $x++) { 
     $emailResult .= 'Call #' . $x; 
     // then doing an API call 
     return $emailResult; 
    } 
} 
0

請按照示例進行操作。我希望這能幫到您。

<?php 
echo blabla(); 


function blabla(){ 

$emailMessage = "some text|"; 

$emailMessage .= "some more text|"; 

function foo() { 
$emailResult=""; 
for ($x = 1; $x <= 20; $x++) { 

    $emailResult .= "Call #".$x."|"; 

} 

    return $emailResult; 
} 

$res = foo(); 

$emailMessage .=$res; 

$emailMessage .= "last line of text"; 

return $emailMessage; 

} 
?>