0

Folks,

I am learning about Global Variables and Super Globals. Been experimenting. The following works. I am able to 'return $GLOBALS['z4']'.

Example 1

<?php

//Php holds all 'Global Variables' in an array. Format: $GLOBALS[index]; The 'index' holds the name of the variable.

$x4 = 4; //'Global Variable' as outside function. It now exists in "Super Global" Variable array as: $GLOBALS['x4'].
$y4 = 4; //'Global Variable' as outside function. It now exists in "Super Global" Variable array as: $GLOBALS['y4'].

function addition_4()
{
    $GLOBALS['z4'] = $GLOBALS['x4'] + $GLOBALS['y4']; //A new "Global Variable" '$z4' is created inside the function.
    return $GLOBALS['z4'];
}

echo addition_4();

?>

But on this following one, why am I unable to 'return $z4' ?

Example 2

<?php

//Php holds all 'Global Variables' in an array. Format: $GLOBALS[index]; The 'index' holds the name of the variable.

$x4 = 4; //'Global Variable' as outside function. It now exists in "Super Global" Variable array as: $GLOBALS['x4'].
$y4 = 4; //'Global Variable' as outside function. It now exists in "Super Global" Variable array as: $GLOBALS['y4'].

function addition_4()
{
    $GLOBALS['z4'] = $GLOBALS['x4'] + $GLOBALS['y4']; //A new "Global Variable" '$z4' is created inside the function.
    return $z4; //WHY I GET ERROR: "Notice: Undefined variable: z4 in ..." ?
}

echo addition_4();

?>

Folks, since this following exists "$GLOBALS['z4']" in both examples above, then I was able to "return $GLOBALS['z4'] on the 1st example.

Now, since "$GLOBALS['z4']" exists in both examples, then that also means "$z4" also exists in both examples. Correct ? So, why I am unable to "return $z4" on the 2nd example ? Why I get error that, $z4 is undefined ?

0 Answers0