0

I have a separate file where I include variables with thier set value. How can I make these variables global?

Ex. I have the value $myval in the values.php file. In the index.php I call a function which needs the $myval value.

If I add the include(values.php); in the beggining of the index.php file it looses scope inside the function. I will call the same variable in multiple functions in the index.php file.

3
  • 3
    You might want to ask yourself why you're using a global variable and if there's a better way to achieve the same thing. Global variables are nearly always a bad idea. Commented Nov 4, 2011 at 13:41
  • include has nothing to do with variable scope, is it that hard to investigate? Commented Nov 4, 2011 at 13:47
  • If I say that something has a global scope, I expect that when I include the file where the variable was defined as such in my script that it will remain in global scope and can be treated as such. Yes, after finding out that it doesn't work, it seems like include just redefines the variable for me every time my script runs. the PHP documentation doesn't talk about this at all. Commented Nov 5, 2011 at 3:01

5 Answers 5

7

Inside the function, use the global keyword or access the variable from the $GLOBALS[] array:

function myfunc() {
  global $myvar;
}

Or, for better readability: use $GLOBALS[]. This makes it clear that you are accessing something at the global scope.

function myfunc() {
  echo $GLOBALS['myvar'];
}

Finally though,

Whenever possible, avoid using the global variable to begin with and pass it instead as a parameter to the function:

function myfunc($myvar) {
  echo $myvar . " (in a function)";
}

$myvar = "I'm global!";
myfunc($myvar);
// I'm global! (in a function)
Sign up to request clarification or add additional context in comments.

Comments

2

Use inside your function :

global $myval;

PHP - Variable scope

Comments

1

Using the global keyword in the beginning of your function will bring those variables into scope. So for example

$outside_variable = "foo";

function my_function() {
   global $outside_variable;
   echo $outside_variable;
}

Comments

1

Is there a reason why you can't pass the variable into your function?

myFunction($myVariable)
{
  //DO SOMETHING
}

It's a far better idea to pass variables rather than use globals.

Comments

0

Same as if you declared the variable in the same file.

function doSomething($arg1, $arg2) {
    global $var1, $var2;
    // do stuff here
}

Comments

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.