Joshua
Joshua

Reputation: 4320

Do globals interfere with required files in PHP?

I need to edit a variable (array) that is defined outside of the function, so I can use it in another function further in. The easiest way I can think of is to define it as global inside the function, but I have many required files involved as well.

The documentation of global variables says that it can be used "anywhere in the program." Does that imply throughout all files (is it global in a sense of across all files) or is it just the file it's in (locally global, if that makes sense).

I did find a question about globals on this site that suggests passing it by reference, but I have this function implemented extensively in other files and requiring them to have an additional variable in their calls would be obnoxious to say the least.

Upvotes: 3

Views: 257

Answers (4)

aib
aib

Reputation: 47001

If a lot of functions grouped in a file require access to some common state, chances are you need to turn them into a class. That's pretty much the definition of a class.

Or you could turn the array into a class and have functions call methods on it.

Perhaps a singleton or a registry (2) could help.

Note that most OOP implementations pass a reference to the object as a method's first parameter, hidden (C++, PHP) or not (C, Python).

Upvotes: 0

phihag
phihag

Reputation: 288210

Globals are shared among all files. By the way, instead of declaring them with global $variable;, you should use $GLOBALS['variable'] to make explicit that you're accessing a global variable.

Upvotes: 1

Michael Irigoyen
Michael Irigoyen

Reputation: 22957

If the file you declare the global in is in memory, then that variable is available for you to use. But, if you don't include or require the file the global is declared in on a certain page, it will not be available to you.

Order is also important. If you try to call the global variable before the include or require of the file you set it in, it will be unavailable.

Upvotes: 1

Paul Sonier
Paul Sonier

Reputation: 39510

If you define your variable global within the function, you will be referring to the globally scoped variable, and changes to that variable made within your function will be visible to other functions that use that global variable, whatever files they're in, so long as the inclusion / execution order is correct.

Upvotes: 3

Related Questions