The following code produces a warning:
<?php
$GLOBALS['foo'] = "Example content<BR><BR>";
echo $foo; // that works!
Test();
function Test()
{
echo $foo; // that doesn't work!
}
?>
The warning is:
Notice: Undefined variable: foo
How come ?
Inside the function, $foo is out of scope unless you call it as $GLOBALS['foo'] or use global $foo. Defining a global with $GLOBALS, although it improves readability, does not automatically reserve the variable name for use in all scopes. You still need to explicitly call the global variable inside lower scopes to make use of it.
function Test()
{
echo $GLOBALS['foo'];
// Or less clear, use the global keyword
global $foo;
echo $foo;
}
It's even possible to have both a local and a global $foo in the same function (though not at all recommended):
$GLOBALS['foo'] = "foo! :)";
function getFoo()
{
$foo = "boo :(";
echo $GLOBALS['foo'] . "\n"; // Global $foo
echo $foo; // Local scope $foo since it has no global keyword
}
getFoo();
// foo! :)
// boo :(
Review the PHP documentation on variable scope and the $GLOBALS documentation for more examples.
You will need to refer to it via the $GLOBALS array all the time. Read about variable scope to get the full descriptve answer.
<?php
$GLOBALS['foo'] = "Example content<BR><BR>";
echo $foo; // that works!
Test();
function Test()
{
echo $GLOBALS['foo']; // that doesn't work!
}
?>
you can change your code to:
function Test() {
global $foo;
echo $GLOBALS['foo'];
echo $foo;
}
you have to declare which global variables you access from your PHP function. See: http://php.net/manual/en/language.variables.scope.php
Related
Question
why the unset function is different between global and $GLOBALS ?
here is my code , the $GLOBALS version will echo nothing ,but the global will echo "hi".
//$GLOBALS version
<?php
function foo()
{
unset($GLOBALS['bar']);
}
$bar ="hi";
foo();
echo $bar;
?>
the code above echo nothing
but when i change $GLOBALS['bar'] to global $bar ,it echo "hi"
//global version
<?php
function foo()
{
global $bar;
unset($bar);
}
$bar = "hi";
foo();
echo $bar;
?>
I have search in google and php manual , but it seems not detail about this problem .
what is the difference between GLOBALS and GLOBAL?
A true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. When you use unset() it unsets the variable that is referencing the global variable, the same as other references. When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed. For example:
$a = 1;
//assign a reference to $a
$b =& $a;
unset($b);
var_dump($a);
Yields: int(1) See Unsetting References.
When you access $GLOBALS you are accessing a superglobal array and unsetting the actual variable contained in the array.
I'm learning PHP, and I came around to the global variable concept. I don't quite understand why this variable is getting an "undefined variable" error.
function function1() {
global $totalGeneral;
$totalGeneral = 42;
}
function function2(){
echo $totalGeneral;
}
I expected 42 to be printed out. Instead I get:
Notice: Undefined variable: totalGeneral
Reading about variable scope at the PHP manual, I thought that adding "global" was enough to make the variable global.
You forgot to include the global in your second function. Without it, it is never in scope.
Just because you use the global keyword doesn't mean the rules don't apply. Global variables are always out of scope inside of a function unless you use the global keyword (or pass it as a parameter or, the case of a closure, use the use keyword).
function function1() {
global $totalGeneral;
$totalGeneral = 42;
}
function function2(){
global $totalGeneral;
echo $totalGeneral;
}
You need to make your variable global in function2() too.
Also global directive only say to php to take variable from globals, so you need to declare your variable first, so:
$totalGeneral = 69;
function function1() {
global $totalGeneral;
$totalGeneral = 42;
}
function function2(){
global $totalGeneral;
echo $totalGeneral;
}
I have a problem with the below:-
//index.php
<?php
define('PATH','Ajfit/');
/* Get all the required files and functions */
require(PATH . 'settings.inc.php');
require(PATH . 'inc/common.inc.php');
?>
//setting.inc.php
<?php
$settings['language']='English';
?>
//inc/common.inc.php
<?php
//global $settings, $lang, $_SESSION; //$setting = null????
$language = $settings['language']; //$language is still null
?>
when i try and access the global variable $settings within common.inc.php it is set null even though i set the variable within setting.inc.php. If i debug, when i step out of setting.inc.php the $settings valiable is set within the index.php, however when i step into common.inc.php the $settings valiable is set to null.
Does anyone have any ideas?
Answer: In the inc/common.inc.php file, you don't need to use the global keyword, the variable is already accessible. Using global redefines the variable, and is thus made null.
Explanation:
Variable Scope is the key here. The global keyword is only required when scope changes. The scope of regular files (including include()s) is all the same, so all of your variables are accessible by any php in the same scope, even if it comes from a different file.
An example of where you need to use global is inside of functions. The scope of a function is different than that of plain php, which is different from class scope, and so on.
Example:
//foo.php
$foo = "bar";
echo $foo; //prints "bar" since scope hasn't changed.
function zoo() {
echo $foo; //prints "" because of scope change.
}
function zoo2() {
global $foo;
echo $foo; //prints "bar" because $foo is recognized as in a higher scope.
}
include('bar.php');
//bar.php
echo $foo; //prints "bar" because scope still hasn't changed.
function zoo3() {
echo $foo; //prints "" for the same reason as in zoo()
}
function zoo4() {
global $foo;
echo $foo; //prints "bar" for the same reason as in zoo2()
}
More Information:
If you want more information on when to use global and when not to, check the php.net documentation on variable scope.
Get array declared outside function to every function without passing argument in php
<?php
$arr2= array('00','12','23','73');
function f1() {
print_r($arr2);
}
f1();
?>
Here we can pass the array f1($arr2), but I want to know whether we acess array inside the function 'f1' without passing, something like setting global or some else ?
I want only to know, whether it is possible or not ?
use global:
function f1() {
global $arr2;
print_r($arr2);
}
However, as #steven already point out, it is considered bad practice.
These thread talk about why global variable is considered bad:
Are global variables in PHP considered bad practice? If so, why?
PHP global in functions
It's possible using globals however it is typically considered a bad practice.
Example from php.net:
<?php
function test() {
$foo = "local variable";
echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";
echo '$foo in current scope: ' . $foo . "\n";
}
$foo = "Example content";
test();
?>
Use global $arr2:
<?php
$arr2= array('00','12','23','73');
function f1()
{
global $arr2;
print_r($arr2);
}
f1();
?>
I have two PHP files. In the first I set a cookie based on a $_GET value, and then call a function which then sends this value on to the other file. This is some code which I'm using in join.php:
include('inc/processJoin.php');
setcookie("site_Referral", $_GET['rid'], time()+10000);
$joinProc = new processJoin();
$joinProc->grabReferral($_COOKIE["site_Referral"]);
The other file (processJoin.php) will then send this value (among others) to further files which will process and insert the data into the database.
The problem I'm having is that when the grabReferral() function in processJoin.php is called, the $referralID variable isn't being defined on a global scale - other functions in processJoin.php can't seem to access it to send to other files/processes.
I've tried this in processJoin.php:
grabReferral($rid) {
global $ref_id;
$ref_id = $rid;
}
someOtherFunction() {
sendValue($ref_id);
}
But the someOtherFunction can't seem to access or use the $ref_id value. I've also tried using define() to no avail. What am I doing wrong?
you have to define the global var in the second function as well..
// global scope
$ref_id = 1;
grabReferral($rid){
global $ref_id;
$ref_id = $rid;
}
someOtherFunction(){
global $ref_id;
sendValue($ref_id);
}
felix
personally, I would recommend the $GLOBALS super variable.
function foo(){
$GLOBALS['foobar'] = 'foobar';
}
function bar(){
echo $GLOBALS['foobar'];
}
foo();
bar();
DEMO
This is a simple and working code to initialize global variable from a function :
function doit()
{
$GLOBALS['val'] = 'bar';
}
doit();
echo $val;
Gives the output as :
bar
The following works.
<?php
foo();
bar();
function foo()
{
global $jabberwocky;
$jabberwocky="Jabberwocky<br>";
bar();
}
function bar()
{
global $jabberwocky;
echo $jabberwocky;
}
?>
to produce:
Jabberwocky
Jabberwocky
So it seems that a variable first declared as global inside a function and then initalised inside that function acquires global scope.
The global keyword lets you access a global variable, not create one. Global variables are the ones created in the outermost scope (i.e. not inside a function or class), and are not accessible inside function unless you declare them with global.
Disclaimer: none of this code was tested, but it definitely gets the point across.
Choose a name for the variable you want to be available in the global scope.
Within the function, assign a value to the name index of the $GLOBALS array.
function my_function(){
//...
$GLOBALS['myGlobalVariable'] = 42; //globalize variable
//...
}
Now when you want to access the variable from code running in the global scope, i.e. NOT within a function, you can simply use $ name to access it, without referencing the $GLOBALS array.
<?php
//<global scope>
echo $myGlobalVariable; //outputs "42"
//</global scope>
?>
To access your global variable from a non-global scope such as a function or an object, you have two options:
Access it through the appropriate index of the $GLOBALS array. Ex: $GLOBALS['myGlobalVariable'] This takes a long time to type, especially if you need to use the global variable multiple times in your non-global scope.
A more concise way is to import your global variable into the local scope by using the 'global' statement. After using this statement, you can reference the global variable as though it were a local variable. Changes you make to the variable will be reflected globally.
//<non global scopes>
function a(){
//...
global $myGlobalVariable;
echo $myGlobalVariable; // outputs "42"
//...
}
function b(){
//...
echo $GLOBALS['myGlobalVariable']; // outputs "42"
echo $myGlobalVariable; // outputs "" (nothing)
// ^also generates warning - variable not defined
//...
}
//</non global scopes>
Please use global variables in any language with caution, especially in PHP.
See the following resources for discussion of global variables:
http://chateau-logic.com/content/dangers-global-variables-revisited-because-php
http://c2.com/cgi/wiki?GlobalVariablesAreBad
The visibility of a variable
I hope that helped
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>