Enhance function access to external variables
P粉165522886
P粉165522886 2023-10-16 17:43:35
0
2
493

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粉165522886
P粉165522886

reply all(2)
P粉645569197

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;
P粉734486718

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 section, especially the following subsections:

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template