Log in

View Full Version : Resolved Limited use of "global" variable



djr33
06-10-2010, 12:57 AM
I'm creating a function that I want to "import" a variable from global scope and I want to modify this variable. I do NOT want to save these modifications to the global variable, but only within the function.


The only way I know to do this is to copy it manually within the function, but this seems like a waste of system resources (note that in the actual code I'm using "$var" is a huge array).

function myfunc() {
global $var;
$varcopy = $var;
$varcopy++;
}

What I'd really like is a keyword instead of global like from_global_as_copy.
Any ideas?

This isn't crucial (my function is working fine), but I would like, at some point, to optimize the code.



EDIT: I seem to have found my answer. Instead of using global $var; I should use:
$var = $GLOBALS['var'];

Does anyone have any other thoughts on this?

fileserverdirect
06-10-2010, 01:27 AM
What exactly were you trying to optimize? And if your code was working fine without the $_GLOBALS superglobal, why did you need it. Enlighten us.

djr33
06-10-2010, 03:59 AM
It's part of a complex system, more than is worth trying to explain here.

The situation is this:
1. I have a very big array of data. Let's call it "cars".
2. I want to have a function called searchcars().
3. Within that, I want to search through $cars and find the "good" ones (or whatever).
4. I want to only keep the "good" ones and remove the others.
5. Then I want to do other things within that function like display them, save them, email them, etc.
6. I want to NOT change the global value of the array $cars-- just inside the function.


In other words, I want to get the value of global $cars, but I do not want to link the local $cars to the global $cars.