Rick
Rick

Reputation: 2308

PHP: Global variable scope

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.

Upvotes: 0

Views: 3354

Answers (5)

Michael Berkowski
Michael Berkowski

Reputation: 270617

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)

Upvotes: 7

psx
psx

Reputation: 4048

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.

Upvotes: 1

Josh Pennington
Josh Pennington

Reputation: 6408

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;
}

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

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

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

Upvotes: 0

Leto
Leto

Reputation: 2674

Use inside your function :

global $myval;

PHP - Variable scope

Upvotes: 2

Related Questions