增強函數對外部變數的訪問
P粉165522886
P粉165522886 2023-10-16 17:43:35
0
2
418

我在外面有一個陣列:

$myArr = array();

我想讓我的函數存取其外部的數組,以便它可以向其中添加值

function someFuntion(){
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
}

如何為函數賦予變數正確的作用域?

P粉165522886
P粉165522886

全部回覆(2)
P粉645569197

您可以使用匿名函數

$foo = 42;
$bar = function($x = 0) use ($foo) {
    return $x + $foo;
};
var_dump($bar(10)); // int(52)

或您可以使用箭頭函數

$bar = fn($x = 0) => $x + $foo;
P粉734486718

預設情況下,當您位於函數內部時,您無權存取外部變數。


如果您希望函數能夠存取外部變量,則必須在函數內部將其宣告為全域變數:

function someFuntion(){
    global $myArr;
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
}

有關詳細信息,請參閱變數範圍 .

但請注意,使用全域變數不是一個好的做法:這樣,您的函數就不再獨立了。


更好的主意是讓你的函數回傳結果

function someFuntion(){
    $myArr = array();       // At first, you have an empty array
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;      // Put that $myVal into the array
    return $myArr;
}

並像這樣呼叫函數:

$result = someFunction();


您的函數還可以接受參數,甚至處理透過引用傳遞的參數

function someFuntion(array & $myArr){
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;      // Put that $myVal into the array
}

然後,像這樣呼叫該函數:

$myArr = array( ... );
someFunction($myArr);  // The function will receive $myArr, and modify it

有了這個:

  • 您的函數接收外部陣列作為參數
  • 並且可以修改它,因為它是透過引用傳遞的。
  • 這比使用全域變數更好:您的函數是一個單元,獨立於任何外部程式碼。


有關詳細信息,您應該閱讀函數 部分,特別是以下子部分:

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!