Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP multiple encapsulated functions global variable scope

This is a solution for a problem that I had and could not find an answer for anywhere. It involves Global Variable Scope and multiple functions.

Basically, I wanted one function to declare variables and then have a second nested function use those variables. This works fine when a script declares the variables and then calls a function that uses those variables after declaring global $var1, $var2;.

However, I had problems with the nested function seeing variables that the parent function declared, using the same code logic as for a script calling a function.

The solution was to write:

function function_1(){
  global $var1, $var2;
  $var1=0;
  $var2=0;
  function function_2(){
     global $var1, $var2;
  }
  function_2();//call to nested function.
}

All variables interact properly in this case.

If you state 'global' after you declare the variables in function_1, you simply wipe out the value of the variables (you declare new variables with no values?).

Hope this helps someone :)

Greg

like image 878
Greg Avatar asked Nov 05 '22 16:11

Greg


2 Answers

Don't use global variables. Use use ($var1,$var2) so you do not need to globalize your variables

like image 130
genesis Avatar answered Nov 09 '22 15:11

genesis


To illustrate what genesis was saying, do the following:

function func1($a, $b) // <-- function DEFINITION for func1
{
    // do stuff wit $a and $b

    func2($a, $b); // <-- function INVOCATION of func2 within func1
}

func2($y, $z) // <-- function DEFINITION for func2
{
    // do stuff with $y and $z
}

// --------------------------------

$param1 = "some value";
$param2 = "some other value";

func1($param1, $param2); // <-- explicit INVOCATION of func1... func2 is also invoked within

Never use the 'global' keyword to pass parameters into a function. Functions have argument lists for a reason.

like image 38
Major Productions Avatar answered Nov 09 '22 15:11

Major Productions