This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 7 years ago.
I declared a new variable $var at the top of my document. Afterwards, I called a function which should output this variable.
Unfortunately, I get the following message:
Notice: Undefined variable: var
This is my code:
$var = "abc";
func ();
function func() {
echo $var;
}
In PHP, functions cannot access variables that are within the global scope unless the keyword global is used to 'import' the variable into the function's scope.
You would fix it by doing this:
function func() {
global $var;
echo $var;
}
Read more about scoping here: http://php.net/manual/en/language.variables.scope.php
Any variable used inside a function is by default limited to the local function scope.
In PHP global variables must be declared global inside a function if they are going to be used in that function.
Global variables can also be accessed using $GLOBALS although I would avoid using that unless absolutely necessary.
A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array.
Worth mentioning:
It's worth linking to this discussion on globals and why you may not want to use them: Globals are evil
. I'd say there is a preference to use classes instead, or simply pass in the variable as an argument to the function. I won't say not to use globals but at the very least be mindful of its use.
This is because the scope of the variable, either you define it as global, or you pass it as a parameter.
Check the comments under this post:
Variables Scope
The scoping of your variable is wrong. You will need to either pass it as a function parameter or declare it as Global in the function. Please review function scoping.
You could do something like this:
$var = "abc";
func ();
function func() {
global var;
echo $var;
}
Related
I have heard using global variables is not good, however I am just trying to understand how the PHP language works. I am a beginner in the coding world.
Why can global variables be created within functions? Whether it is through the use of the global keyword or through a superglobal variable. I thought these two actions were used to access global variables in a function. I thought the only way you can create a global variable is to create it outside a function; in the global scope. I have looked at many different websites including w3schools.com and php.net
This is just some simple code I created to try and understand the way global variables work with functions:
<?php
function sample1() {
global $a;
echo $a = "this ";
}
sample1();
function sample2() {
echo $GLOBALS['$b'] = "is ";
}
sample2();
function sample3() {
global $c;
$c = "an ";
}
sample3();
echo $c;
function sample4() {
$GLOBALS['$d'] = "example ";
}
sample4();
echo $GLOBALS['$d'];
?>
This is the result of the code:
this is an example
All of the code works, but I don't understand how I created a global variable on any of these blocks of code? The global variables were not created outside of the functions. How can they be created inside of a function? What am I missing? Any response is appreciated - If possible, please keep the answer simple - I would like to discuss this further in the comment section, because I'm sure I will have follow up questions - Thank you
Variables can be created in the global scope in the two ways you just did - there's nothing saying that a function can't create (or change) a variable in the global scope - WHEN you explicitly ask for it through $GLOBALS or the global keyword.
The issue is that your belief "I thought the only way you can create a global variable is to create it outside a function; in the global scope." is not an exact statement. When you're using $GLOBALS and global, you're referring to the global scope. You're introducing a reference to the global scope inside your function.
With global you're in effect linking the local reference to the global reference, while with $GLOBALS you're explicitly referencing the global scope (which internally inside PHP can be introduced to the local scope in the same way).
In that case you're explicitly saying "I want this variable to be available in the global scope, make it so!" and PHP does what you're asking it to. This behaviour differ between languages, but as you've discovered for PHP, it's allowed.
It's not something I would recommend using in any way - it makes your code very hard to follow and argue around, so consider it an esoteric detail.
I've got two isset function
function getPlayers(){
if (isset($_POST['select']))
{
global $t1select;
global $t2select;
The code above is part of the first function, notice the two global variables I declared, I did this because I would like to use them in my second functions:
function PlayerAttributes(){
if (isset($_POST['teamselect'])) {
The function above is my second function.
The Problem
When I try to refer to the global variables in the second function, I get the error message "Undefined variable: t1select "
What am I doing wrong?
You have to put global $var in every function you wish to use them in, not just one.
Varibles should be declared as global in every function that is going to use them. Otherwise they will be only for the local scope of the function.
Another approach is to use the $GLOBALS['varname'] syntax. This will work without any declarations.
Consider the following situation..
$var = 'Lots of information';
function go($var) {
// Do stuff
}
Now, when PHP exits the function, does it clear the memory automatically of all local variables within the function or should I be doing:
unset($var);
...within the function on any local variables that store large amounts of data?
It will clear itself inside the function scope. This means that the $var parameter of the function will no longer exists after the function call.
Notice that $var = 'Lots of information'; is outside the function block therefore will not be cleared automatically. In this case $var in the global scope and $var in the function scope are two different things and inside the function block only $var in the function scope will exists.
This question goes to the concept of Variable Scope. Inside the function, the variables are "contained" and unless declared global, are not related to variables of the same name outside of the function. So if you created a large variable inside a function, and you want to unset() it, you would need to unset() inside the function. This page is important, especially the part about "global" and "static" variables. PHP also has a way to pass a variable by reference using an ampersand in front of the variable name. In that case, the function is operating on the variable itself, not the function's copy of the variable.
http://php.net/manual/en/language.variables.scope.php
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
what is the difference between “GLOBAL” and “STATIC” variable in php
if we create a static variable inside a function, this variable exists in further using of the function... and as far as I know global variable does the same.
now what's the benefit of using static variables?
The lexical scope of a static static variable is restricted to the function body – you cannot access the variable outside the function.
However, its value will be remembered across multiple calls of the same function.
Global variables exist in global scope and can be accessed from anywhere in your code (you have to use the global keyword or $GLOBALS array inside functions though)
A static variable just implies that the var belongs to a class but can be referenced without having to instantiate said class. A global var lives in the global namespace and can be referenced by any function in any class. Global vars are always frowned upon because they're so easily misused, overwritten, accidentally referenced, etc. At least with static vars you need to reference via Class::var;
Lets say I have this:
function myFunc()
{
global $distinct_variable;
die ($distinct_variable);
}
function anotherFunc()
{
$distinct_variable = 'Hello World';
myFunc();
}
anotherFunc();
For anotherFunc() to correctly show 'Hello World', it must be written like this
{
global $distinct_variable;
$distinct_variable = 'Hello World';
myFunc();
}
Now it will show the message, but why must I global $distinct_variable; in anotherFunc() since it is a global in myFunc() which is within anotherFunc()
Yes, I know that variables inside functions won't go outside of them, but I was thinking it should have worked...
Could someone explain why isn't it working?
Thanks.
Thank you for your answers, I get it now :)
A global variable is exactly that - it exists in the GLOBAL scope ONLY.
Everything in PHP (except superglobals) exist in only one scope - be that the global scope, or the scope of a function/method. Scope does not cascade - so just because you have a variable in an "outer" function does not make it available to an "inner" function.
Similarly, global fetches the variables defined in the GLOBAL scope only (the top-most scope), not simply "the scope above this one, from which I was called". This is what you tried to do, but it absolutely will not work. This level of finer-grained control is what function arguments/return values are for.
Each function has its own symbol table. There is also a global symbol table. Just because one function is being called from within another doesn't mean that the variables declared global in one are global in the other, or inherited from the other. They still refer to the variable in the "local" symbol table by default.
Doing global $somevar; echo $somevar boils down to echo $GLOBALS['somevar'];. That $GLOBALS superglobal does not include variables that were defined inside a function: only truly 'global' vars, which exist at the top level of the script.