1

i have an application done in php and all configuration variables are loaded in a big $conf variable at the beginning of the script.

What is the better way to communicate this configuration variable to all other functions ?

make it a parameter of every function ? or use it with "global $conf;" statement in every function ?

is there a better way to do ?

Thanks

Fredv
  • 543
  • 1
  • 8
  • 21
  • 1
    One approach is to split your configuration up into sections and have each component of your application load only the configuration section it needs access to. Alternatively you can store the info in your database and read it from there. – lucifurious Apr 02 '11 at 20:15

3 Answers3

4

Use PHP constants.

For ponies sake, avoid using global variables at all costs :)

EDIT

Some explanations about "avoiding global variables at all costs" and possible alternatives:

Community
  • 1
  • 1
Frosty Z
  • 20,022
  • 9
  • 74
  • 102
  • Avoidance *at all costs*. Gosh, I don't even want to imagine the cumbersome outcome. – mario Apr 02 '11 at 20:17
  • @mario sorry for my english :) – Frosty Z Apr 02 '11 at 20:18
  • Nah, it's not the english. You've run aground some pretty bad meme advise. -- That being said, constants are often (= not always) a good choice to harbour some config settings. – mario Apr 02 '11 at 20:21
  • "You've run aground some pretty bad meme advise." - For what global variables should be used then ? – Frosty Z Apr 02 '11 at 20:30
  • Application-wide config settings are pretty much one of the more useful (and not groundless *quite common*) use cases for them. – mario Apr 02 '11 at 20:49
  • As Mario said, my variable is an application-wide config settings. I can't imagine using constants for that – Fredv Apr 02 '11 at 22:26
  • @mario: Unjustified code duplication is *quite common* too, but it doesn't means that it's a good practice. ==> Edited answer, too add some (IMO) useful resources. Hopefully, Fredv could find there some better alternatives to the use of global variables, which can lead too easily to uncontrolled dependencies between many code parts of a given project, potentially raising very time-consuming problems. – Frosty Z Apr 03 '11 at 13:46
  • I've removed the dumbest of your links. Btw, Stackoverflow has many more previous exact duplicates on that topic; all heaps more objective than that fat ass meme headline. http://stackoverflow.com/questions/1557787/are-global-variables-in-php-considered-bad-practice -- The logical lapse in avoiding globals becomes apparent when you realize how useful your code becomes without actual global variables like $_POST and $_GET. – mario Apr 03 '11 at 13:53
  • frosty, thanks for the links. I know globals may be considered as bad practice but i have seen nice, efficient php sources using that and, well, as long as you don't overuse them it seems to work fine .. i have always made a very small use of globals in my coding .. just wanted to know better about how to deal with that on php – Fredv Apr 03 '11 at 16:11
  • @mario: Concerning the removed link, although I do not 100% agree with Gordon's answer, he gives a good idea of the user-defined global variables danger (no warning when such variables have been incidentally modified or "redeclared", potentially leading to incomprehensible behavior and big headache). $_POST and $_GET are automatically defined by PHP and documented as such; you don't even need the 'global' keyword to use them. No much to do with user-defined globals obviously leading to mess if not used and documented with extreme caution. – Frosty Z Apr 03 '11 at 20:29
2

Make a configuration class that stores the options. Make it a singleton PHP Manual describes that here. This is just an alternative to global variables. It would allow you to define a method to load options from a file or a php array and store them in the class. Other classes can use the configuration object by getting the single instance and accessing the data.

I think this is better than a global variable as the other answer also says. But it still lets you define options as arrays, or even nested arrays if you want (and set up your class accordingly)

Matt
  • 5,283
  • 9
  • 51
  • 93
0

Your use of a single global-scoped variable $conf is perfectly fine. Many PHP applications do that. But there are drawbacks to combat.

In particular it's often more effort to write global $conf in each function where you want to access them. In that case I would recommend a simple global wrapper function instead:

function conf($key, $sub="") {
    global $conf;
    if (defined($key))
        { return constant($key); }
    elseif ($sub)
        { return $conf[$key][$sub]; }
    else
        { return $conf[$key]; }
}

This allows you to write conf("setting1") or conf("main", "opt3") whereever you need it. Still you can access the global $conf where that is more suitable. As extra bonus you can make this wrapper function more intelligent, by allowing it to query alternative settings etc. Also see how easy it is to also sneak in conf("CONSTANT") support.

Keeping this adds some flexibility in defining your configuration settings. Personally I use a similar approach, albeit with defining the array step-wise rather than at once:

$app_config["title"] = ...;
$app_config["editor.btns"] = ...;
define("RESTRICTED_MODE", true);

I'm preferring the array() approach, but transitioning to an ini-file for storage at a later point is not a problem. Also you can still make your config array read-only if the need arises. For that just define an:

class Read_Only_Array extends ArrayObject { function offsetSet() {} }
$conf = new ReadOnlyArray($conf);

So it's still accessible as array, but you easily established what others use cumbersome registries or syntactic workarounds for.


The "globals are evil" meme is completely baloney. It's parrotted on SO by cargo cult programmers with a desire for oversimplification and newcomers who glance over bold headlines without understanding the language semantics.

In your case, you just use a single $conf variable, and do not pollute the shared scope. When it is coherently accessed from the whole application, then it's not an issue. You should however strictly avoid to modify contents at runtime (use Read_Only_Array if need be). Create a secondary $app_var[] aray for that, and keep your config settings static.

mario
  • 138,064
  • 18
  • 223
  • 277
  • i usually don't really like globals but as i have seen this $conf way of coding in several php sources, i think it can be done :) your function idea is nice to avoid declaring global $conf everywhere, thanks – Fredv Apr 03 '11 at 16:07
  • Why not, but couldn't some `function blah() { global $conf; ... $conf = 'blah'; ... }` from a dumb developer or external library silently ruin all that ? – Frosty Z Apr 03 '11 at 20:47
  • @FrostyZ: Possible, but not overly likely. And as said one can make it a read-only array if such a need *factually* arises. – mario Apr 03 '11 at 21:01
  • @mario: assigning a read-only array to a variable, won't make that variable read-only. `$conf = 'blah';` will simply erase the read-only array stored into `$conf`. About global variables: the only fact that they can be silently changed or "redeclared" (unlike constants for example), even if such a situation is not *overly likely*, is more than enough for me to call them evil. This awful reputation didn't pop out from nowhere. I'm telling this because I've experienced problems, not because I want to oversimplify or just repeat something without understanding. – Frosty Z Apr 04 '11 at 12:13
  • @FrostyZ: I could make up a *fictional* example using runkit or classkit that "accidentially" screws your alternative Registry or Singleton aproach. Doesn't make it a problem in reality. Having stumbled upon problems with strpos() or being ticked off by abstract classes once years ago doesn't warrant declaring them evil either. That wording is still indicative of cargo cult programming. (It seems an extensive post is in order for this meme indoctrination..) – mario Apr 04 '11 at 12:24
  • @mario: Comparing global vars problems with strpos() or abstract classes ones, is comparing pears and coconuts. I didn't pretend either that Registry or Singleton were the ultimate solution to store configuration data. However, especially for a beginner, it's still far easier to incidentally silently redefine a global, than redefining a class, a class method, a constant, an "ini" file, a pony, whatever. – Frosty Z Apr 04 '11 at 18:28
  • @FrostyZ: You came up with the `Unjustified code duplication` strawmen, so I picked one of my own. There are many more pitfalls for newbies, no discussion. But using that or other assumptions as rationalization for workarounds doesn't seem useful to me. (And I deem a warning or notice sufficient to catch such hypothetical errors at the development stage anyhow. A bit much discussion on unlikely issues.) – mario Apr 04 '11 at 18:36
  • @mario: I've talked about unjustified code duplication to simply explain that a *quite common practice* does not make it necessarily a *good practice*, because you raised the argument that globals are *quite common* in app-wide settings to justify their use. You're free to think that issues with global are unlikely and hypothetical. Good luck then :) – Frosty Z Apr 05 '11 at 11:28
  • @FrostyZ: It just doesn't get more likely from repeating it more often. But regarding your example problem, how about a noob writing `$_GET = 'blah'` instead - how more likely than a $db= overwrite do think that is? And since people use heaps of isset()s due to the clean coding meme, how would you ever notice? – mario Apr 05 '11 at 12:00
  • @mario: I think we could uselessly debate over and over on the topic "are serious issues with globals likely/unlikely ?"... To help refocus on the real topic, I'm simply tired of seeing overuse of globals vars, messy / spaghetti coding with them, leading to inextricable issues, because config settings or 'ghost parameters' got silently changed, on projects I have to maintain. Maybe I should more blame poor coders than globals (PEBKAC > "globals are evil") ? :) – Frosty Z Apr 05 '11 at 18:48
  • However I still prefer to use techniques allowing my global config settings to be 'as read-only as possible' once they are set, to avoid bad surprises. – Frosty Z Apr 05 '11 at 18:50
  • @FrostyZ: I cannot argue with that. Config storages which are misused for signaling are not what I long for (regardless of if it's a global array or registry). But the PHP manual is more to blame than the existence of any syntax construct. Not elaborating on proper use is not less uneducative than telling noobs *Xyz is always bad*. Though it's probably more lack of experience than tutorial-caused misuse. – mario Apr 05 '11 at 19:05