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?
Be forewarned, generally people stick away from globals as it has some downsides.
You could try this
That would make it so you aren't relying on Globals.
The one and probably not so good way of achieving your goal would using global variables.
You could achieve that by adding
global $myArr;
to the beginning of your function. However note that using global variables is in most cases a bad idea and probably avoidable.The much better way would be passing your array as an argument to your function:
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 :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 :
And call the function like this :
Your function could also take parameters, and even work on a parameter passed by reference :
Then, call the function like this :
With this :
For more informations about that, you should read the Functions section of the PHP manual, and,, especially, the following sub-sections :
Two Answers
1. Answer to the asked question.
2. A simple change equals a better way!
Answer 1 - Pass the Vars Array to the __construct() in a class, you could also leave the construct empty and pass the Arrays through your functions instead.
Answer 2 - A simple change however would put it inline with modern standards. Just declare your Arrays in the Class.
Both options output the same information and allow a function to push and retrieve information from an Array and sub Arrays to any place in the code(Given that the data has been pushed first). The second option gives more control over how the data is used and protected. They can be used as is just modify to your needs but if they were used to extend a Controller they could share their values among any of the Classes the Controller is using. Neither method requires the use of a Global(s).
Output:
Array Custom Content Results
Modals - Count: 5
a
b
c
FOO
foo
JS Custom - Count: 9
1
2B or not 2B
3
42
5
car
house
bike
glass