Rosamunda Rosamunda - 2 months ago 8
PHP Question

PHP: global variable won't work as expected when used with the global keyword inside a function

I'm learning PHP, and I came around to the global variable concept. I don't quite understand why this variable is getting an "undefined variable" error.

function function1() {
global $totalGeneral;
$totalGeneral = 42;
}

function function2(){
echo $totalGeneral;
}


I expected 42 to be printed out. Instead I get:


Notice: Undefined variable: totalGeneral


Reading about variable scope at the PHP manual, I thought that adding "global" was enough to make the variable global.

Answer

You forgot to include the global in your second function. Without it, it is never in scope.

Just because you use the global keyword doesn't mean the rules don't apply. Global variables are always out of scope inside of a function unless you use the global keyword (or pass it as a parameter or, the case of a closure, use the use keyword).

function function1() {
    global $totalGeneral;
    $totalGeneral = 42;
}

function function2(){
    global $totalGeneral;
    echo $totalGeneral;
}