Rosamunda
Rosamunda

Reputation: 14980

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.

Upvotes: 2

Views: 100

Answers (2)

fiction
fiction

Reputation: 586

You need to make your variable global in function2() too.

Also global directive only say to php to take variable from globals, so you need to declare your variable first, so:

$totalGeneral = 69;

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

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

Upvotes: 2

John Conde
John Conde

Reputation: 219814

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;
}

Upvotes: 2

Related Questions