/    Sign up×
Community /Pin to ProfileBookmark

Why Global Variable Shows Undefined When Using The return Function ?

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 ?

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@NogDogApr 06.2021 — Please don't ask the same question in yet another thread. Closing this thread.
Copy linkTweet thisAlerts:
@NogDogApr 06.2021 — {"locked":true}
×

Success!

Help @developer_web spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.10,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...