让我的函数访问外部变量

bre*_*ett 69 php scope function

我外面有一个阵列:

$myArr = array();
Run Code Online (Sandbox Code Playgroud)

我想让我的函数访问它外面的数组,以便它可以为它添加值

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

如何为函数提供正确的范围?

Pas*_*TIN 119

默认情况下,当您在函数内部时,您无权访问外部变量.


如果希望函数有权访问外部变量,则必须global在函数内声明它:

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

有关更多信息,请参阅可变范围.

但请注意,使用全局变量不是一个好习惯:有了这个,你的函数就不再是独立的了.


更好的想法是让你的函数返回结果:

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;
}
Run Code Online (Sandbox Code Playgroud)

并调用这样的函数:

$result = someFunction();
Run Code Online (Sandbox Code Playgroud)


您的函数也可以获取参数,甚至可以处理通过引用传递的参数:

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

然后,像这样调用函数:

$myArr = array( ... );
someFunction($myArr);  // The function will receive $myArr, and modify it
Run Code Online (Sandbox Code Playgroud)

有了这个 :

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


有关更多信息,请阅读PHP手册的" 函数"部分,尤其是以下小节:

  • @Machine:相当不错的问题^^*(我已经编辑了我的答案了几次以添加更多的信息;也许它被低估了,因为不够完整,起初......它可能与全球有关,人们不喜欢......)* (3认同)
  • @Machine Anti-Global先生@Coronatus已经确定完全可行的答案是错误的.他的1,662名代表让他说得对...... (3认同)

Max*_*s.c 21

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


Tyl*_*ter 10

Global $myArr;
$myArr = array();

function someFuntion(){
    global $myArr;

    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
}
Run Code Online (Sandbox Code Playgroud)

需要预先警告,一般人们会避开全局,因为它有一些缺点.

你可以试试这个

function someFuntion($myArr){
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
    return $myArr;
}
$myArr = someFunction($myArr);
Run Code Online (Sandbox Code Playgroud)

这样就可以让你不依赖于Globals.


Amy*_*y B 8

$myArr = array();

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

    return $myArr;
}

$myArr = someFunction($myArr);
Run Code Online (Sandbox Code Playgroud)

  • 愚蠢的downvoting.当然,这是整个帖子中唯一正确的答案. (6认同)
  • 如果对片段进行解释,这个答案的质量将大大提高。 (2认同)