Forum Moderators: coopster
*******************************
<?php
$data1 = 1;
for($i=1; $i < 1000; $i++) {
cool_func();
}
exit;
function cool_func() {
global $data1;
print $data1;
}
********************************
Now that works fine! And if I remove the global $data1; from the function it won't display - just as expected.
So I got the syntax right. I'm just wondering why the global HAS to go within the function. Why can't it be at the top of the code?
I have to call the function 1000 times so it seems a waste of resources to declare the global 1000 times?
function printbar() {
$foo = "bar\n";
echo $foo;
}
echo $foo;
printbar();
echo $foo;
---------------
Output would be:
foo
bar
foo
the global variable $foo is a different variable from the $foo inside printbar(). You have to declare it as global so that PHP knows you mean to be talking about the $foo in the global namespace rather than the local namespace.
Get yourself going on a big project, and you'll really appreciate this!
for($i=1; $i < 1000; $i++) {
cool_func();
}function cool_func(){
for ($i=0; $i < 20; $i++) {
; // Doesn't matter for the example
}
}
If any variable whose name was the same as one defined in the global scope were simply treated as a reference to that global variable, then this would be an infinite loop. Obviously, the correct behavior is to do something 20,000 times, not infinitely many :)
there is another way, to get the var $data1 kind of 'global':
function cool_func(&$t)
{
print $t;
$t = 'printed:'.$t;
}
and pass $data1 as parameter to your function:
cool_func($data1);
that's normally what a function is for, you won't need global vars in it. you can pass vars by reference (the &) to modify them in the function (if you need to).