0

I have not been able to find a good example for this particular case. Most people who ask this question have a more complex use case and so the answer usually involves a complex solution. I simply have a few variables at the beginning of the script that need to be available throughout all the code including several functions. Otherwise I would have to set it in each function, and considering this is a user set value, changing it all throughout the code is just not possible.

<?php
//**** Example User Config Area **** 
$name = "blah";
$tag = "blah";
//**********************************

function taco() {
    echo $name; //this function needs to use these user set variables
    echo $tag;
}
?>

Everyone says NOT to use global variables. Is this a case where global variables actually DOES make sense? If not, what should I do here to make this work?

It should be noted that those values do not change in the program. They only change if the user edits them. Like a DB location or a username etc.

Atomiklan
  • 3,630
  • 7
  • 34
  • 56
  • well there are many eays to declare a variable, as a public variable inside the class, global, or session if you define the variable inside the class should be a good option and safe – Marcos Brinner Oct 26 '17 at 22:28

2 Answers2

2

Just pass these variables:

function taco($name, $tag) {
    echo $name;
    echo $tag;
}
// and
taco($name, $tag);
cn007b
  • 14,506
  • 6
  • 48
  • 62
1

There are two main ways you can do configuration in PHP.

The first is to create a configuration object that you can pass around to each function. Some people consider this a little clunky, but it does get around using global variables.

That being said, if you're just trying to store configuration details, a global variable is not a bad option and has been discussed on this site before.

You need to think about your use case. If you're dealing with something that could create a race condition, then global variables are of course a bad idea. If you just want to store some static information to reference throughout your code... it's not the end of the world.

Jacobm001
  • 4,032
  • 4
  • 29
  • 49
  • 1
    I like to combine both of these options by using a singleton config object. That way you can inject the config object if you want, or you can reach back out to the global namespace to get it if you don't want to. [Example here](https://tehplayground.com/tIhpeSOQnTBBVvIW) – syndicate_software Oct 26 '17 at 22:43