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.

1
  • 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 Commented Oct 26, 2017 at 22:28

2 Answers 2

2

Just pass these variables:

function taco($name, $tag) {
    echo $name;
    echo $tag;
}
// and
taco($name, $tag);
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I think I understand the problem now! I wasn't passing the variables to the function, just defining them in the function.
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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.