0

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 ?

4
  • Try passing as a parameter Commented Jun 16, 2017 at 19:29
  • it works fine, but what if I want to use is as global variable? Commented Jun 16, 2017 at 19:33
  • 1
    Some hostings have implicitely set register_globals directive to off. Check your php.ini. Generally, global variables are not considered as a good practice. Can you avoid them? Commented Jun 16, 2017 at 19:33
  • Your code is pretty inter-winded which makes it hard to track scope and execution order. $some_global_var = 'abc'; might but must not set a global variable (in your case it is a local variable), also include_once will make the assignment to only run once. Commented Jun 16, 2017 at 19:47

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

Where should I put global?
Incorrect. Even if you global the variable in the include it doesn't solve the problem
I mocked this just to double check. PHP throws out Parse error: syntax error, unexpected '=', expecting ',' or ';' in if I global the variable in the include

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.