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.
Related
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;
}
I have six functions that require a global variable. In an attempt to reduce redundancy, I wrote a new function that is triggered rather than triggering all six. This one function has a global $var that is required by the other functions.
So, it looks like this
function one_function_for_the_rest() {
global $importantVar;
functionOne();
functionTwo();
functionThree();
}
but the global variable is not being seen by the called functions. Am I doing this incorrectly, or is this a limitation I was not aware of?
You're not doing it correctly as the variable is defined when on_function_for... is called. An easier way for this would be just to have $importantVar; at the start of the code.
Or wrap your functions inside a class and put the variable inside the class.
e: so basically do : function myFunc($important) { stuff } and when calling the function do myFunc($importantVar)
example :
$asd = "lol";
class myclass {
public function lol($asd) {
echo $asd;
}
}
$obj = new myclass;
$obj->lol($asd);
You're not doing it correctly. Each function either needs to use the global scope identifier, like global $importantVar;, or have $importantVar passed as a parameter. Otherwise, the other functions don't have $importantVar in their respective scopes.
Simply calling a function from within one_function_for_the_rest does not tell that other function anything about global variables or variables used in one_function_for_the_rest. In technical terms, your function calls do not bring $importantVar into the respective scopes of functionOne, functionTwo, or functionThree.
PHP does not have the same scoping rules as most other languages have. That is the downside to not having to declare variables with var as in JavaScript or other similar constructs.
Basically in PHP, every function used is only available in that function. There are three exceptions:
The global keyword
The $this variable inside objects. This one is also "magic" as it's also available inside anonymous functions defined inside a class.
When declaring an anonymous functions you can bind variables to it using use.
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
Why does THIS not work when called via e.g. wd(1) (it always returns '-2')?
$zoom=$user['zoom'];
function wd($hrs){
return $hrs*$zoom-2;
}
But THIS works fine:
function wd($hrs){
return $hrs*30-2;
}
Assuming this was a casting problem, I tried all sorts of variations like
(int)$hrs * ((int)$zoom)
or
(int)$hrs * (float)$zoom
but no success :(
Any help would be appreciated.
(And BTW, does it matter whether the function is located within
include('header.php')
-- although I tried it both within and outside the header?)
EDIT: You should pass that variable as an argument to the function, but if you absolutely need to keep the variable global, do the following.
You need to bring the global into scope:
$zoom=$user['zoom'];
function wd($hrs){
global $zoom;
return $hrs*$zoom-2;
}
This isn't a casting issue - it's because you're trying to use a variable that's out of scope.
Whilst you'll need to read the PHP docs for the full low-down, at a basic level, you can only access variables that are defined within the same function or method. (Although you can use the global keyword to access global variables. That said, global variables are less than ideal.)
As such, you could simply update your function to also pass in 'zoom' as a parameter as follows:
function wd($hrs, $zoom){
return $hrs*$zoom-2;
}
$zoom=$user['zoom'];
function wd($hrs){
// there is no variable $zoom within the function's visibility scope
// so you will get a "Notice: undefined variable 'zoom'" here.
return $hrs*$zoom-2;
}
see http://docs.php.net/language.variables.scope
I'm having trouble with global variables in php. I have a $screen var set in one file, which requires another file that calls an initSession() defined in yet another file. The initSession() declares global $screen and then processes $screen further down using the value set in the very first script.
How is this possible?
To make things more confusing, if you try to set $screen again then call the initSession(), it uses the value first used once again. The following code will describe the process. Could someone have a go at explaining this?
$screen = "list1.inc"; // From model.php
require "controller.php"; // From model.php
initSession(); // From controller.php
global $screen; // From Include.Session.inc
echo $screen; // prints "list1.inc" // From anywhere
$screen = "delete1.inc"; // From model2.php
require "controller2.php"
initSession();
global $screen;
echo $screen; // prints "list1.inc"
Update:
If I declare $screen global again just before requiring the second model, $screen is updated properly for the initSession() method. Strange.
Global DOES NOT make the variable global. I know it's tricky :-)
Global says that a local variable will be used as if it was a variable with a higher scope.
E.G :
<?php
$var = "test"; // this is accessible in all the rest of the code, even an included one
function foo2()
{
global $var;
echo $var; // this print "test"
$var = 'test2';
}
global $var; // this is totally useless, unless this file is included inside a class or function
function foo()
{
echo $var; // this print nothing, you are using a local var
$var = 'test3';
}
foo();
foo2();
echo $var; // this will print 'test2'
?>
Note that global vars are rarely a good idea. You can code 99.99999% of the time without them and your code is much easier to maintain if you don't have fuzzy scopes. Avoid global if you can.
global $foo doesn't mean "make this variable global, so that everyone can use it". global $foo means "within the scope of this function, use the global variable $foo".
I am assuming from your example that each time, you are referring to $screen from within a function. If so you will need to use global $screen in each function.
You need to put "global $screen" in every function that references it, not just at the top of each file.
If you have a lot of variables you want to access during a task which uses many functions, consider making a 'context' object to hold the stuff:
//We're doing "foo", and we need importantString and relevantObject to do it
$fooContext = new StdClass(); //StdClass is an empty class
$fooContext->importantString = "a very important string";
$fooContext->relevantObject = new RelevantObject();
doFoo($fooContext);
Now just pass this object as a parameter to all the functions. You won't need global variables, and your function signatures stay clean. It's also easy to later replace the empty StdClass with a class that actually has relevant methods in it.
You must declare a variable as global before define values for it.
The global scope spans included and required files, you don't need to use the global keyword unless using the variable from within a function. You could try using the $GLOBALS array instead.
It is useless till it is in the function or a class. Global means that you can use a variable in any part of program. So if the global is not contained in the function or a class there is no use of using Global