Giving my function access to outside variable
$foo = 42;
$bar = function($x = 0) use ($foo){
return $x + $foo;
};
var_dump($bar(10)); // int(52)
UPDATE: there is now support for arrow functions, but i will let for someone that used it more to create the answer
By default, when you are inside a function, you do not have access to the outer variables.
If you want your function to have access to an outer variable, you have to declare it as global
, inside the function :
function someFuntion(){
global $myArr;
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
}
For more informations, see Variable scope.
But note that using global variables is not a good practice : with this, your function is not independant anymore.
A better idea would be to make 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 could also take parameters, and even work on a parameter 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 received the external array as a parameter
- And can modify it, as it's passed by reference.
- And it's better practice than using a global variable : your function is a unit, independant of any external code.
For more informations about that, you should read the Functions section of the PHP manual, and,, especially, the following sub-sections :
- Functions arguments
- Returning values