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 ?

  • "Now, since "$GLOBALS['z4']" exists in both examples, then that also means "$z4" also exists in both examples. Correct ?" <- This is *not* correct. Have a look at the linked answer, and at [this page in the PHP manual](https://www.php.net/manual/en/language.variables.scope.php) which explain the difference between local and global variables, and what `$GLOBALS` is doing there. – IMSoP Apr 06 '21 at 19:43
  • I saw the error of my ways. This thread may now be closed. Thanks. – studentprogrammer2020 Apr 11 '21 at 16:23

0 Answers0