tags:

views:

52

answers:

4

Is there a way to get around having to reference Global variables inside a function in PHP?

I just hate having to use the 'global' keyword for every variable, and I've been told that using constants (as an alternative) in PHP affects performance badly.

+1  A: 

You can try using $GLOBALS

Sadat
A: 

Just send the variable into the function like so:

function yourfunction ($variable1, $variable2) { 
    ... 

  }

 //Call the function:
 yourfunction ($variable1, $variable2);
play
+2  A: 

if you have to use many global variables inside of your function, something has been designed wrong.

Using even a few global variables considered bad practice, making code non-obvious.
And constants are not a solution despite of falseness of that "badly performance" rumor

If you need to use many variables inside of a function, consider array use

$data   = array("one","two","three");
$result = myfunc($data);

simple, reliable and readable

with more detailed explanation of what this function do and what all these variables for, you can get more precise answer.

Col. Shrapnel
What about all configuration variables? Aren't they stored in global variables? I dont think that placing configuration variables in global variables is wrongly designed.I believe I'll have to start using the $GLOBALS['variable_name'] method instead.
Basil Musa
@Basil configuration variables should be arranged into array in the first place! so, typing single `global $cfg;` wont hurt you too much
Col. Shrapnel
+1 globals are bad, m'kay?
George Marian
A: 
Rimian