/    Sign up×
Community /Pin to ProfileBookmark

Why $GLOBAL Variable Shows Error That Variable Undefined ?

Folks,

Check this why I get undefined variable $z error when I write this: return $z.

[code]
<?php

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

$x = 1; //’Global Variable’ as outside function. It now exists in “Super Global” Variable array as: $GLOBALS[‘x’].
$y = 2; //’Global Variable’ as outside function. It now exists in “Super Global” Variable array as: $GLOBALS[‘y’].

function addition_4()
{
$GLOBALS[‘z’] = $GLOBALS[‘x’] + $GLOBALS[‘y’]; //A new “Global Variable” ‘$z’ is created inside the function.
return $z; //This shows ‘Undefined variable’ error. Have to write like this to not see error: return $GLOBALS[‘z’].
}

echo addition_4();
echo $z; //This gets echoed. Doesn’t show error. So, why return $z above shows error ?
?>
[/code]

Did not $z get defined here:
**$GLOBALS[‘z’] = $GLOBALS[‘x’] + $GLOBALS[‘y’];**

This following code is ok as I write:
**return $GLOBALS[‘z’];**

And not write:
**return $z.**

[code]
<?php

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

$x = 1; //’Global Variable’ as outside function. It now exists in “Super Global” Variable array as: $GLOBALS[‘x’].
$y = 2; //’Global Variable’ as outside function. It now exists in “Super Global” Variable array as: $GLOBALS[‘y’].

function addition_3()
{
$GLOBALS[‘z’] = $GLOBALS[‘x’] + $GLOBALS[‘y’]; //A new “Global Variable” ‘$z’ is created inside the function.
return $GLOBALS[‘z’];
}

echo addition_3();

?>
[/code]

to post a comment
PHP

18 Comments(s)

Copy linkTweet thisAlerts:
@NogDogApr 06.2021 — https://www.php.net/manual/en/reserved.variables.globals.php

> **Description**

> An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.


When you are inside of a function, you are not in the global scope. (You are in a local scope only available within that function.) Therefore the super-global array $GLOBALS is available, but not the actual global variables it represents.

Pro tip: if you're using $GLOBALS within a function, 99 times out of 100 (at least) you're probably writing sloppy/poor/easily-broken code. That being said, if you really, really, _really_ want to do something like that (instead of passing values explicitly via the function arguments/parameters), I suppose you could do:
[code=php]
$x = 4;
$y = 5;
function test() {
global $x, $y;
return $x * $y;
}
echo test();
// 20
[/code]

Much better, though:
<i>
</i>$x = 4;
$y = 5;
function test2($a, $b) {
return $a * $b;
}
echo test2($x, $y);
// 20
Copy linkTweet thisAlerts:
@NogDogApr 06.2021 — PS: Read this: https://www.php.net/manual/en/language.variables.scope.php (at least the first few paragraphs)
Copy linkTweet thisAlerts:
@VITSUSAApr 07.2021 — I agree with NogDog, this is the right source to solve this problem.
Copy linkTweet thisAlerts:
@developer_webauthorApr 08.2021 — @NogDog#1629994

What you told me above, I already know as I been reading last week or two or so ago:

https://www.tutorialspoint.com/php/php_functions.htm

https://www.geeksforgeeks.org/how-to-declare-a-global-variable-in-php/

So, what did I learn from those 2 tutorial sites one or two weeks back ?

I learnt that the variables outside the function is global variable and if I need to use that global variable inside a function then I need to declare it like so from inside the function:

<i>
</i>global $x.


Or, I could write like this:
<i>
</i>$GLOBALS['x'].

The second option, I didn't like much and things weren't clear to me. Seems you don't like it too. I thought best to still learn about it as you never know when it may become handy. Hence, I opened this thread 2 nights ago.

I also learnt another thing one or two weeks ago.

You see, I used to write functions like this:
<i>
</i>function custom_function()
{
code
}


But I see in tutorials $vars passed in function params like so:
<i>
</i>function custom_function($new)
{
code
}

I never could understand why some functions had empty braces and others filled.

Then the first link, which I gave above, made things clear.

Then I learnt, it's best to write the function like this with the NULL:
<i>
</i>function custom_function($new=NULL)
{
code
}

That way, if you forget to pass a variable into the function making mistake like so:
<i>
</i>custom_function()


when you should have written something like so:
<i>
</i>custom_function($var)


<i>
</i>custom_function(1)


Then you won't get any error.


Then I learnt about the "&" where original value of global variable will change/not change based on whether the "&" exists or not like so:
<i>
</i>custom_function($var)


<i>
</i>custom_function(&amp;$var).


I also learnt about these operators:

**+=

*=

/=

-=**


Eg.
<i>
</i>&lt;?php

$x = 1;

function function_7(&amp;$new=NULL)
{
global $x;
echo $y = $new+=$new;
}

function_7($x);
echo $x;


I also was testing with the "return" and without the "return".

1.
<i>
</i>
$var_2 = '2'; //This is global variable as it is declared outside functions.

function new_function_1() //Since no global variable is passed inside the function, on this line through the function definition braces, will have to mention the global variable inside the function. Like format: $GLOBALS['var_name'].
{
echo 'Value is: ' .$GLOBALS['var_2'] .'!'; //This line wouldn't have been necessary had the global variable $var_2 been passed as a parameter on the function definition's braces. Like so: function function_name($var);
}

new_function_1(); //Echoing the function name (function call) is NOT necessary since AN echo is mentioned inside the function.


2.
<i>
</i>$var_2 = '2'; //This is global variable as it is declared outside functions.

function new_function_2() //Since no global variable is passed inside the function, on this line through the function definition braces, will have to mention the global variable inside the function by adding 'global' prior to it. Like so: global $var.
{
$string = 'Value is: ' .$GLOBALS['var_2'] .'!'; //This line wouldn't have been necessary had the global variable $var_2 been passed as a parameter on the function definition's braces. Like so: function function_name($var);
return $string;
}

echo new_function_2(); //Echoing the function name (function call) is necessary since no echo is mentioned inside the function and the returned value has to be echoed on this line here.


Note how on one example I echoed the function call while on the other I didn't. Note on one example there is the "return" and on the other example there is not.

You see how I experiment and test and learn things myself without tutorials going into that much indepth giving examples ? I build my own examples and test and experiment and when I come across obstacles or confusion then I find my way to this form to hassle NogDog. Next time I 'll start the harassment if I don;t get any replies or a proper one at that which I understand. Lol!

So, I have managed to learn about these basics a week or two ago. So, don't worry.

Then there was a week or two learning break. Then I continued my learning 2 nights ago.

Actually, when I opened this thread 2 nights ago, I was reading:

https://www.w3schools.com/php/php_superglobals_globals.asp

Nevertheless, your reply has been helpful as a confirmation to what I learnt, that I learnt correctly.

Sometimes you read something but have doubts whether you understood the tutorial precisely or not and need confirmation that what you understood is not incorrect. Your above reply became that confirmation.

The two examples you gave above, I first learnt from a tutorial your first example then learnt from the same tutorial your second example a week or two ago.
Copy linkTweet thisAlerts:
@developer_webauthorApr 08.2021 — @NogDog,

I am copy-pasting my file that I used to experiment things and make notes of the results.

From it you can easily gather what I learnt correctly or incorrectly. Yeah, I know, you don;t have time to wade through all this but if you ever have time and wonder how much I learnt so far then have a sneak peek here ...
<i>
</i>&lt;?php
//This is template. All codes done from memory. No copying or copy &amp; pasting from tutorials or anywhere like forums. No borrowed codes. Can use these codes 'AS IS' by copying into my business php scripts.
?&gt;

&lt;?php
//Tutorials from: https://www.tutorialspoint.com/php/php_functions.htm
?&gt;

&lt;?php
//STEP 1: No passing of global variables to inside a function as it's function parameter. No function function_name($var) but function function_name().
//Eg 1a.
//NOTE: Difference between Eg1 &amp; Eg2 is that former does not pass global variable as function parameter for variable to work inside the function and so it is needed to delcare the global variable as 'global' from inside the function. Whereas with eg2 the global variable is passed into the function, as a function parameter, to work inside the function and so no need to declare the global variable as "global' from inside the function.
$var_1 = '1'; //This is global variable as it is declared outside functions.

function new_function_1() //Since no global variable is passed inside the function, on this line through the function definition braces, will have to mention the global variable inside the function by adding 'global' prior to it. Like so: global $var.
{
global $var_1; //This line wouldn't have been necessary had the global variable $var_1 been passed as a parameter on the function definition's braces. Like so: function function_name($var);
echo "Value is $var_1!"; //Echoing the function name (function call) is NOT necessary since AN echo is mentioned inside the function.
}

new_function_1();


//Eg 1b.
$var_2 = '2'; //This is global variable as it is declared outside functions.

function new_function_1() //Since no global variable is passed inside the function, on this line through the function definition braces, will have to mention the global variable inside the function. Like format: $GLOBALS['var_name'].
{
echo 'Value is: ' .$GLOBALS['var_2'] .'!'; //This line wouldn't have been necessary had the global variable $var_2 been passed as a parameter on the function definition's braces. Like so: function function_name($var);
}

new_function_1(); //Echoing the function name (function call) is NOT necessary since AN echo is mentioned inside the function.


//Eg 1c.
$var_2 = '2'; //This is global variable as it is declared outside functions.

function new_function_2() //Since no global variable is passed inside the function, on this line through the function definition braces, will have to mention the global variable inside the function by adding 'global' prior to it. Like so: global $var.
{
$string = 'Value is: ' .$GLOBALS['var_2'] .'!'; //This line wouldn't have been necessary had the global variable $var_2 been passed as a parameter on the function definition's braces. Like so: function function_name($var);
return $string;
}

echo new_function_2(); //Echoing the function name (function call) is necessary since no echo is mentioned inside the function and the returned value has to be echoed on this line here.


//Eg2.
//NOTE: Difference between Eg1 &amp; Eg2 is that former does not pass global variable as function parameter for variable to work inside the function and so it is needed to delcare the global variable as 'global' from inside the function. Whereas with eg2 the global variable is passed into the function, as a function parameter, to work inside the function and so no need to declare the global variable as "global' from inside the function.
$var_2 = '2'; //This is global variable as it is declared outside functions.

function new_function_2($parameter)
{
echo "Value is $parameter!";
}

new_function_2($var_2); //Echoing the function name (function call) is NOT necessary since AN echo is mentioned inside the function.


//Eg3.
function new_function_3($parameter=NULL) //Best to add '$param=NULL' ('$var=NULL') so if by mistake no parameters are passed then get no errors on this line for missing parameter.
{
echo "Value is $parameter!";
}

new_function_3(); //Echoing the function name (function call) is NOT necessary since AN echo is mentioned inside the function.
?&gt;


&lt;?php
//STEP 2: Can use strings as function names when calling the function.
function new_function()
{
echo 'Hello!';
}

$function_name = 'new_function'; //Function name is a string.
echo $function_name(); //Function is getting called by identifying the function name from a string.

?&gt;


&lt;?php
//STEP 3: Passing Variables from outside function to inside function as function parameters. Passing via function braces: function function_name($param_1,$param_2);
//Eg1: Difference between eg1 &amp; eg2 is latter uses 'return'.
function combine_values_1($value_1,$value_2) //The 2 values, mentioned inside the function definition braces on the function call line, get added to these two variables mentioned inside the function definition braces.
{
$sum = $value_1+$value_2;
echo 'The Sum of two Values is: '.$sum; //Due to this echo, no need to echo the function call, like so: echo
}
//NOTE: No need to echo the function call since an echo has been made from inside the function definition. No need to write like this: echo combine_values_1(1,2). Only need to echo the function call if the final result, inside the function definition, is not echoed from inside the function defition.
combine_values_1(1,2); //The 2 values, mentioned inside the braces, get added to the two variables mentioned inside the function definition braces.


//Eg2.
//Difference between eg1 &amp; eg2 is latter uses 'return'.
//Difference between eg2 &amp; eg3 is latter echoes the function call to get the function's return value. While former adds the function call to a variable and echoes that variable. Note on eg2 &amp; eg 3 how the functions have been called.
function combine_values_2($value_1,$value_2) //The 2 values, mentioned inside the function definition braces on the function call line, get added to these two variables mentioned inside the function definition braces.
{
$sum = $value_1+$value_2;
return $sum;
}

$new_value = combine_values_2(1,2); //The 2 values, mentioned inside the braces, get added to the two variables mentioned inside the function definition braces.

echo 'The Sum of two Values is: '.$new_value; //Echoing the variable name, that holds the function name (function call) as it's value, is necessary since no echo is mentioned inside the function and the returned value has to be echoed on this line here.


//Eg3.
//Difference between eg2 &amp; eg3 is latter echoes the function call to get the function's return value. While former adds the function call to a variable and echoes that variable. Note on eg2 &amp; eg 3 how the functions have been called.
function combine_values_3($value_1,$value_2) //The 2 values, mentioned inside the function definition braces on the function call line, get added to these two variables mentioned inside the function definition braces.
{
$sum = $value_1+$value_2;
return $sum;
}
//Echoing the function name (function call) is necessary since no echo is mentioned inside the function and the returned value has to be echoed on this line here.
echo 'The Sum of two Values is: '.combine_values_3(1,2); //The 2 values, mentioned inside the braces, get added to the two variables mentioned inside the function definition braces.

?&gt;


&lt;?php
//STEP 4A
//'&amp;' Examples. Original Variable value changes when adding '&amp;' prior to variable name inside function braces.

//Eg 1.
$original = 2;
echo '$original= ' .$original; echo '&lt;br&gt;'; //echoes: 2.

function change_var_1(&amp;$new) //Added '&amp;' prior to variable name inside function braces. Now original value of variable will change.
{
$new = 1; //$new value is forced to '1'. And not added by '1' unlike Eg2.
}

change_var_1($original); //The value of the variable, mentioned inside the braces, get added to the variable mentioned inside the function definition braces.

echo '$original= ' .$original; echo '&lt;br&gt;'; //echoes: 1. Note: Variable value ($original) has changed.


//Eg2.
$original = 2;
echo '$original= ' .$original; echo '&lt;br&gt;'; //echoes: 2.

function change_var_2(&amp;$new)
{
$new += 1; //$new value is NOT forced to '1'. But is added by '1' unlike Eg1.
}

change_var_2($original); //The value of the variable, mentioned inside the braces, get added to the variable mentioned inside the function definition braces.

echo '$original= ' .$original; echo '&lt;br&gt;'; //echoes: 3. Note: Variable value ($original) has changed.
?&gt;

&lt;?php
//STEP 4B
//nO '&amp;' Examples. Original Variable value not changes due to not adding '&amp;' prior to variable name inside function braces.
//On following 2 examples, original value of variable ($original) will NOT change.

//Eg 1.
$original = 2;
echo '$original= ' .$original; echo '&lt;br&gt;'; //echoes: 2.

function change_var_3($new) //Not added '&amp;' prior to variable name inside function braces. Now original value of variable will NOT change.
{
$new = 1; //$new value is forced to '1'. And not added by '1' unlike Eg2.
}

change_var_3($original); //The value of the variable, mentioned inside the braces, get added to the variable mentioned inside the function definition braces.

echo '$original= ' .$original; echo '&lt;br&gt;'; //echoes: 2. Note: Variable value ($original) has NOT changed.


//Eg2.
$original = 2;
echo '$original= ' .$original; echo '&lt;br&gt;'; //echoes: 2.

function change_var_4($new)
{
$new += 1; //$new value is NOT forced to '1'. But is added by '1' unlike Eg1.
}

change_var_4($original); //The value of the variable, mentioned inside the braces, get added to the variable mentioned inside the function definition braces.

echo '$original= ' .$original; echo '&lt;br&gt;'; //echoes: 2. Note: Variable value ($original) has NOT changed.
?&gt;


&lt;?php
//STEP 5: Checks if a function() exists or not. Checks both built-in functions and user defined functions.
$functions = array("function_exists","in_array");

$i = 0;
foreach($functions as $function)
{
if(function_exists($functions[$i]))
{
echo "$function " .'exists!';
}
}

?&gt;
Copy linkTweet thisAlerts:
@developer_webauthorApr 08.2021 — @NogDog,

Ok. I managed to narrow my question down. My original question was this.

Look at these 2 examples:
<i>
</i>&lt;?php

$x = 1;
$y = 2;

function addition()
{
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; //A new "Global Variable" '$z' is created inside the function.
}

addition();

echo $z; //Since '$z' is present within the $GLOBALS[index] array. It is accessible outside the function.

?&gt;

Can you see I created the two variables outside the function ? They are: $x, $y.

Now can you see I created no variable called $z inside or outside the function ?

But I created the $GLOBALS['z'] inside the function. Right ?

Well, I learnt that, no matter what variable (eg. $nogdog) I create outside the function, it can be called inside the function like so:

$GLOBALS[index].

eg.

$GLOBALS[nogdog].

Php auto creates it or whatever.

The main question or Q1 was, if I don't create the variable $sempervivum but mention inside the function this:

$GLOBALS[sempervivum]

then would php auto create $sempervivum or not ?

I mean can I write outside the function this $sempervivum ?

Based on my following experiment, it seems that I can without any errors.

Check it out:

<i>
</i>&lt;?php

$developer_web = 1;
$nogdog = 2;

function addition()
{
$GLOBALS['sempervivum'] = $GLOBALS['developer_web'] + $GLOBALS['nogdog']; //A new "Global Variable" '$sempervivum' is created inside the function.
}

addition();

echo $sempervivum; //Since '$sempervivum' is present within the $GLOBALS[index] array. It is accessible outside the function.

?&gt;


Can you see the two comments in my above code ? My question is, is that 1st comment correct or not ? That was my 2nd question or Q2.
Copy linkTweet thisAlerts:
@developer_webauthorApr 08.2021 — @NogDog,

Now here is my third question or Q3. Now this is very important NogDog so make sure I understand your upcoming answer. Ok ? Because if I understand your answer fully then I can close this thread.

Let's get straight to the bottom of this. Shall we ?

Here's the code again ...
<i>
</i>&lt;?php

$developer_web = 1;
$nogdog = 2;

function addition()
{
$GLOBALS['sempervivum'] = $GLOBALS['developer_web'] + $GLOBALS['nogdog']; //A new "Global Variable" '$sempervivum' is created inside the function.
}

addition();

echo $sempervivum; //Since '$sempervivum' is present within the $GLOBALS[index] array. It is accessible outside the function.

?&gt;

Based on the above code, I only created two global variables:

$developer_web

$nogdog

I did not create:

$sempervivum.

However, from inside the function, I created:

$GLOBALS['sempervivum']

and php auto created for me, without me manually needing to:

$sempervivum.

Had php not created it, then I never would have been able to do the following outside the function:

**echo $sempervivum**

Now, since php has auto created $sempervivum and I am able to echo that variable from outside the function then why on earth I get error if I try '**returning** the value of **$sempervivum**' ?

Like so:

<i>
</i>&lt;?php

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

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

function addition_4()
{
$GLOBALS['sempervivum'] = $GLOBALS['developer_web'] + $GLOBALS['nogdog']; //A new "Global Variable" '$sempervivum' is created inside the function.
return $sempervivum; //WHY I GET ERROR: "Notice: Undefined variable: z4 in ...." ? Is it because $sempervivum is a global variable that I am trying to call from within this function ? I should only call local variables inside this function ? If so, then how to make this local variable or how to create another variable, a local one, based on this global variable ?"
}

echo addition_4();

?&gt;

Notice my comment on the above code. I need it's question answered. Comment was:

**_"WHY I GET ERROR: "Notice: Undefined variable: z4 in ...." ? Is it because $sempervivum is a global variable that I am trying to call from within this function ? I should only call local variables inside this function ? If so, then how to make this local variable or how to create another variable, a local one, based on this global variable ?"_**

The following code is working, however. Notice the slight differences between the two.

<i>
</i>&lt;?php

$developer_web = 1;
$nogdog = 2;

function addition()
{
return $GLOBALS['sempervivum'] = $GLOBALS['developer_web'] + $GLOBALS['nogdog']; //A new "Global Variable" '**$sempervivum**' is created inside the function.
}

echo addition();

echo $sempervivum; **//Since '$sempervivum' is present within the $GLOBALS[index] array. It should be RETURNED outside the function.**

?&gt;


Note my **bold comment** above.

See if you can answer my Q3.

As for this:

**https://www.php.net/manual/en/language.variables.scope.php**

I already read it a week or two ago but checking it out again since you recommending it, just incase I forgot anything I learnt back then.
Copy linkTweet thisAlerts:
@developer_webauthorApr 08.2021 — @sempervivum,

Do you mind answering my previous post ?
Copy linkTweet thisAlerts:
@NogDogApr 08.2021 — And just for any other new dev seeing this, I will repeat: using globals within functions is sloppy at best and dangerous at worst. I highly recommend **not** using global nor $GLOBALS within your functions, as it makes them too tightly coupled to the code that uses them, making it difficult both to re-use or to test those functions, and potentially causing difficult to debug errors if the code that uses the function changes in any way that affects those variables. Just pass what you need via the function parameters and be done with it.
Copy linkTweet thisAlerts:
@developer_webauthorApr 09.2021 — @NogDog,

I understood your previous post apart from this bit:

"and potentially causing difficult to debug errors if the code that uses the function changes in any way that affects those variables. "

Care to show an example ?

Anyway, I understand what you are saying.

Not to call global vars within the function but pass the global vars as the function params instead. Like so:

<i>
</i>$x = 'vitsusa';
$y = nogdog;
function test2($a, $b) {
return $a * $b;
}
echo test2($x, $y);


Nevertheless, I still need my Q3 answered below, just for my learning purpose as to satisfy my curiosity about the return function here.
---------------------------------------------



Folks,

Ignore my previous post as it had a typo on a code comment.

Ignore:

https://www.webdeveloper.com/d/393534-why-global-variable-shows-error-that-variable-undefined/8

Answer this post instead ....

Now here is my third question or Q3. Now this is very important NogDog so make sure I understand your upcoming answer. Ok ? Because if I understand your answer fully then I can close this thread.

Let's get straight to the bottom of this. Shall we ?

Here's the code again ...
<i>
</i>&lt;?php

$developer_web = 1;
$nogdog = 2;

function addition()
{
$GLOBALS['sempervivum'] = $GLOBALS['developer_web'] + $GLOBALS['nogdog']; //A new "Global Variable" '$sempervivum' is created inside the function.
}

addition();

echo $sempervivum; //Since '$sempervivum' is present within the $GLOBALS[index] array. It is accessible outside the function.

?&gt;

Based on the above code, I only created two global variables:

$developer_web

$nogdog

I did not create:

$sempervivum.

However, from inside the function, I created:

$GLOBALS['sempervivum']

and php auto created for me, without me manually needing to:

$sempervivum.

Had php not created it, then I never would have been able to do the following outside the function:

echo $sempervivum

Now, since php has auto created $sempervivum and I am able to echo that variable from outside the function then why on earth I get error if I try 'returning the value of $sempervivum' ?

Like so:
<i>
</i>&lt;?php

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

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

function addition_4()
{
$GLOBALS['sempervivum'] = $GLOBALS['developer_web'] + $GLOBALS['nogdog']; //A new "Global Variable" '$sempervivum' is created inside the function.
return $sempervivum; //LINE 11: WHY I GET ERROR: Notice: Undefined variable: sempervivum in C:xampphtdocsTemplatestest2.php on line 11
}

echo addition_4();
echo $sempervivum; //THIS SHOWS NO ERROR. ECHOES: 8.

?&gt;
Copy linkTweet thisAlerts:
@developer_webauthorApr 09.2021 — @sempervivum,

Do you know anything about the return function in depth ? Sure you do. Do you mind answering my previous post ?
Copy linkTweet thisAlerts:
@SempervivumApr 09.2021 — ``<i>
</i>function addition_4()
{
$GLOBALS['sempervivum'] = $GLOBALS['developer_web'] + $GLOBALS['nogdog']; //A new "Global Variable" '$sempervivum' is created inside the function.
// Although the line of code that defines the global variable $sempervivum
// is located inside the function addition_4
// this variable is global and therefore cannot be accessed from inside the function
// return $sempervivum; //LINE 11: WHY I GET ERROR: Notice: Undefined variable: sempervivum in C:xampphtdocsTemplatestest2.php on line 11

// This would work although it would not make sense:
return $GLOBALS['sempervivum'];

// This would work either: Define a local variable and return it:
$sempervivum = $GLOBALS['developer_web'] + $GLOBALS['nogdog'];
return $sempervivum;
}<i>
</i>
``
Copy linkTweet thisAlerts:
@NogDogApr 09.2021 — > @developer_web#1630133 difficult to debug errors if the code that uses the function changes

The problem is that the function is tightly coupled to the entire code being used. Any change to that code that in any way affects those global variables will potentially break that function, sometimes in ways that may essentially be "silent".
[code=php]
error_reporting(E_ALL);
ini_set('display_errors', true);

function yuck() {
return $GLOBALS['x'] + $GLOBALS['y'];
}

$x = 2;
$y = 4;
echo yuck();
// 6

// but if for any reason you change the main code so that those
// global variables are not what the function expects....
unset($y);
echo yuck();
// Notice: Undefined index: y in php shell code on line 2
// 2

$y = array(1,2,3);
php > echo yuck();
// Warning: Uncaught Error: Unsupported operand types in php shell code:2
// Stack trace:
// #0 php shell code(1): yuck()
// #1 {main}
// thrown in php shell code on line 2
[/code]


Much better:
<i>
</i>function add($a, $b) {
if(!is_numeric($a) or !is_numeric($b)) {
throw new Exception("Non-numeric value passed to add()");
}
return $a + $b;
}

echo add($x, $y);

add() is now completely independent of the rest of the code base. All it cares is that you supply it 2 parameters that it can perform an arithmetic operation upon. You can re-use that function anywhere in this app or any other app, and it won't be broken if you re-name variable sin that app, etc.
Copy linkTweet thisAlerts:
@developer_webauthorApr 11.2021 — @NogDog#1630158

Thanks NogDog,

Going through your two examples over and over again.

This is what I notice ...

It's best I 'return' a variable from within a function, a variable that is not a global variable but a variable passed as the function parameter. That way, no variables get broken.
<i>
</i>function add($a, $b) {
if(!is_numeric($a) or !is_numeric($b)) {
throw new Exception("Non-numeric value passed to add()");
}
return $a + $b;
}

echo add($x, $y);


$a & $b variables are used as the function parameters. And so, from within the function, you only returned them two variables and no other. No global variable.

That is what caught my eye in your example. Am I spot on or not ?
Copy linkTweet thisAlerts:
@developer_webauthorApr 11.2021 — @Sempervivum#1630136

Oh I get it now what NogDog was saying all along. His answer wasn't clear to me as I ain't that bright. Good, I harassed you into this thread as your example just hit me what NogDog was trying to get through to me.

What your sample code is telling me is that, even though I created the Global Var '$GLOBALS['sempervivum']' from within the function, the $semprevivum did not get auto created because it ain't a global var but a local one. And since I did not define the local one, hence I see error.

Thanks.

You or NogDog may close this thread now if I understood you correctly here.
Copy linkTweet thisAlerts:
@developer_webauthorApr 11.2021 — There is this Local Variable that can only be used inside the function it was created in. That is ok.

Then there is this Global Variable that can only be used outside the function unless you mention it inside the function like so:

global $var.

How the hell is that "global" if it's not easily accessible from within functions ?

Instead they should've called it "international variable" or "sea variable".

And called the local Variable "national variable" or "island variable".

And they should've created a variable that you can use both outside functions and inside functions aslong as you have defined it atleast once ()regardless of where it got defined. Inside function or outside it).

And they should have called it "dimensional variable" as it's available in all dimensions both inside and outside functions without having to write something special such as "global" .

Maybe, one day, I get built my own programming language and call it likewise.

Mmm. Maybe, I create my own custom function to build this "all dimension var" ? Can someone give a try at it and show me the code, to give me a head-start, and I will try taking it from there to further develop it. I have a feeling, pros have tried this in the past. It's pretty obvious this function is needed!
Copy linkTweet thisAlerts:
@developer_webauthorApr 11.2021 — @NogDog,

This example from the manual, I read a week ago and probably many times before in the past years. But I forgot about it.

<i>
</i>
&lt;?php
$a = 1; /* global scope */

function test()
{
echo $a; /* reference to local scope variable */
}

test();
?&gt;

https://www.php.net/manual/en/language.variables.scope.php

Manual:

**_"This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function."_**
Copy linkTweet thisAlerts:
@togelonline01Apr 11.2021 — https://conexioncolombia.com/
×

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 3.29,
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: @darkwebsites540,
tipped: article
amount: 10 SATS,

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

tipper: Anonymous,
tipped: article
amount: 10 SATS,
)...