I have an array outside:
$myArr = array();
I would like to give my function access to the array outside it so it can add values to it
function someFuntion(){ $myVal = //some processing here to determine value of $myVal $myArr[] = $myVal; }
How do I give the function the right scoping to the variable?
You can't access variables declared inside a function from outside a function. The variable belongs to the function's scope only, not the global scope.
If you want to assign a value to a name defined outside the function, then you have to tell Python that the name is not local, but it is global. We do this using the global statement. It is impossible to assign a value to a variable defined outside a function without the global statement.
Variables declared Globally (outside any function) have Global Scope. Global variables can be accessed from anywhere in a JavaScript program. Variables declared with var , let and const are quite similar when declared outside a block.
In this tutorial, you will learn how to change a variable outside of a function in Python. You can use the variable as global in Python which allows you to change or modify the variable values in any other function in Python.
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 :
For more informations about that, you should read the Functions section of the PHP manual, and,, especially, the following sub-sections :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With