增强函数对外部变量的访问
P粉165522886
P粉165522886 2023-10-16 17:43:35
0
2
321

我在外面有一个数组:

$myArr = array();

我想让我的函数访问其外部的数组,以便它可以向其中添加值

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

如何为函数赋予变量正确的作用域?

P粉165522886
P粉165522886

membalas semua(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

有了这个:

  • 您的函数接收外部数组作为参数
  • 并且可以修改它,因为它是通过引用传递的。
  • 这比使用全局变量更好:您的函数是一个单元,独立于任何外部代码。


有关详细信息,您应该阅读函数 部分,特别是以下子部分:

Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!