Home  >  Q&A  >  body text

Enhance function access to external variables

I have an array outside:

$myArr = array();

I want my function to access the array outside of it so it can add values ​​to it

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

How to give variables the correct scope for functions?

P粉165522886P粉165522886393 days ago456

reply all(2)I'll reply

  • P粉645569197

    P粉6455691972023-10-17 13:51:02

    You can use anonymous functions :

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

    Or you can use arrow functions:

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

    reply
    0
  • P粉734486718

    P粉7344867182023-10-17 13:39:45

    By default, when you are inside a function, you do not have access to external variables.


    If you want a function to be able to access an external variable, you must declare it as a global variable inside the function:

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

    For more information, see Variable scope .

    But please note that using global variables is not a good practice: this way your function is no longer independent.


    A better idea is to have your function return the result :

    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;
    }

    and call the function like this:

    $result = someFunction();


    Your function can also accept arguments and even handle arguments passed by reference :

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

    Then, call the function like this:

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

    With this:

    • Your function receives an external array as a parameter
    • and can modify it since it is passed by reference.
    • This is better than using global variables: your function is a unit, independent of any external code.


    For more information, you should read the Functions< PHP 手册的 /a> section, especially the following subsections:

    reply
    0
  • Cancelreply