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粉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;
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:
For more information, you should read the Functions< PHP 手册的 /a> section, especially the following subsections: