1

I have a global variable but I can't call it within a function.

I've tried defining the variable within the function and it fixes it, but I need the variable to be global so I can call it within other functions. I've tried using "global" before the variable name, but that doesn't work either.


$randBoolean = FALSE;

function someFunction(){
       if(!$randBoolean){
       lineBreak();
       $randBoolean = TRUE;
       }
}

someFunction();

I've used global variables in another php doc and it worked just fine. I'm not sure if it's because this global variable is a boolean or not.

2 Answers2

0

You have to declare the variable as global inside the function.

$randBoolean = FALSE;

function someFunction(){
    global $randBoolean;

    if(!$randBoolean){
        //lineBreak();
        $randBoolean = TRUE;
    }
}
echo $randBoolean ? 'TRUE' : 'FALSE' ;
someFunction();
echo $randBoolean ? 'TRUE' : 'FALSE';

RESULT

FALSE
TRUE

Of course you should avoid globals for many reasons so it would be better to pass the variable to the function as a parameter, and in this case pass it by reference so the function can modify its value.

$randBoolean = FALSE;

function someFunction(&$param){

    if(!$param){
        //lineBreak();
        $param= TRUE;
    }
}
echo $randBoolean ? 'TRUE' : 'FALSE' ;
someFunction($randBoolean);
echo $randBoolean ? 'TRUE' : 'FALSE';

RESULT

FALSE
TRUE
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • I wouldn't recommend either of this options. `global` and pass-by-reference are full of traps. Check the duplicate linked below question. – Dharman Jun 27 '19 at 20:58
0

Do you missed the "global" before your $randBoolean. Check the $GLOBALS array. If there is a reference of your variable you did it right.