简体   繁体   中英

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

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.

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.

您可以尝试使用$ GLOBALS

Just send the variable into the function like so:

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

  }

 //Call the function:
 yourfunction ($variable1, $variable2);

A singleton might be worth considering. Also see the registry pattern.

You could also factor out the global into its own function

This is very very basic...
function do_stuff() {
$var = get_something();
//do more stuff
}

function get_something() {
return 'something';
}

Of course you'd need to set the variable too. That should be easy enough with an object or something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM