moonvader
moonvader

Reputation: 21091

PHP access global variable in function inside other function

I have file a.php that looks like

function func_1() {
  inlude_once(b.php);
  $somevar = 'def';
  func_2($somevar);
}

and b.php that looks like

$some_global_var = 'abc';

function func_2($var) {
  global $some_global_var;
  echo $some_global_var.$var;
}

And for some reason I get only def as a result, why func_2 don't see $some_global_var ?

Upvotes: 0

Views: 66

Answers (2)

Chris
Chris

Reputation: 953

put global in front of it.

per the PHP docs

Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.

you may have an issue with an include file getting in the way

Upvotes: 0

Machavity
Machavity

Reputation: 31624

Because you forgot the scope of func_1. So when you include your define this is how your code appears to PHP

function func_1() {
   $some_global_var = 'abc'; // <- this is inside the scope of the parent function!

    function func_2($var) {
      global $some_global_var;
      echo $some_global_var.$var;
    }
  $somevar = 'def';
  func_2($somevar);
}

You're doing it inside func_1. So the variable was never really available in the global scope. If you defined $some_global_var = 'abc'; outside, then it's in the global scope.

What you should do is inject this as an argument instead. Globals are a bad practice

function func_1() {
   $some_global_var = 'abc'; 

    function func_2($var, $var2) {
      echo $var2 . $var;
    }
  $somevar = 'def';
  func_2($somevar, $some_global_var);
}

Upvotes: 2

Related Questions