What exactly is the difference between the GLOBAL and STATIC variables in PHP? And which one is preferable to use, when we want to use a variable in multiple functions?
Thanks.
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;
Global is used to get the global vars which may be defined in other scripts, or not in the same scope.
e.g.
<?php
$g_var = 1;
function test() {
var_dump($GLOBAL['g_var']);
global $g_var;
var_dump($g_var);
}
Static is used to define an var which has whole script life, and init only once.
e.g.
<?php
function test() {
static $cnt = 0;
$cnt ++;
echo $cnt;
}
$i = 10;
while (-- $i) {
test();
}
A global variable is a variable which is defined in a scope and can span to included and required scopes. (in simple terms by scope I mean the php file/function/class)
Here are some examples of how global variables work.
Example 1: Variable declared in scope and used in function using global keyword
<?php
$a = 1;
function add_a() {
global $a;
$a++;
}
add_a();
echo $a;
In the above example we declare variable $a and assign it value 1 in the scope. We then declare a function add_a in the same scope and try to increment the $a variable value. The add_a function is called and then we echo the $a variable expecting the result to display 2.
Example 2: Variable declared in scope and used in function using the $GLOBALS variable
<?php
$a = 1;
function add_a() {
$GLOBALS['a']++;
}
add_a();
echo $a;
The result from example 2 above is exactly the same as the result from example 1.
There is no difference with using the global keyword and the special PHP defined $GLOBALS array variable. However they both have their advantages and disadvantages.
Read more about $GLOBALS on official PHP website $GLOBALS
If you want to span a scope declared variable to a included or required scope see example below.
Example 3:
file a.php
<?php
global $a;
$a = 1;
require 'b.php';
add_a();
echo $a;
file b.php
<?php
function add_a() {
global $a;
$a++;
}
In the above example we have file a.php and b.php. File b.php is required in file a.php because we use a function declared in file b.php. To use the $a variable in file b.php we must first declare $a as global to be used outside the local scope and we do this by first calling global $a and then we define a value like so $a = 1. Variable $a is now available to be used anywhere in any included scopes by first calling global $a before manipulation.
Static Variables
Usually found in classes but in some well developed PHP project you can find them in recursive functions. A static variable is a variable that remembers its value and can be reused every time the function or method is called.
Here are some examples of a static variable in use.
Example 1: Static variable in a function
function add() {
static $a = 1;
$a++;
echo $a;
}
add(); //2
add(); //3
add(); //4
Example 2: Static variable in class
class A {
public static $a = 1;
public static function add() {
self::$a++;
echo self::$a;
}
}
echo A::$a; //1
A::add(); //2
echo A::$a; //2
A::add(); //3
echo A::$a; //3
A::add(); //4
Note that you cannot assign a return value from a function to a static variable. For example you cannot do static $a = rand(). See Example 3 below on how to assign return value to static variable.
Example 3: Assign return variable from function to static variable
function add() {
static $a;
$a = rand();
echo $a;
}
Read more about global and static variables on PHP official website Variable scope
Global variable is created before the function is created, but global keyword is added in function
$g_var = 1;
function test() {
var_dump($GLOBAL['g_var']);
global $g_var;
var_dump($g_var);
}
static is created and declared static in function
function test() {
static $cnt = 0;
$cnt ++;
echo $cnt;
}
$i = 10;
while(--$i) test();
Related
I have code something like this:
<?
$a="localhost";
function body(){
global $a;
echo $a;
}
function head(){
global $a;
echo $a;
}
function footer(){
global $a;
echo $a;
}
?>
is there any way to define the global variable in one place and make the variable $a accessible in all the functions at once? without making use of global $a; more?
The $GLOBALS array can be used instead:
$GLOBALS['a'] = 'localhost';
function body(){
echo $GLOBALS['a'];
}
From the Manual:
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.
If you have a set of functions that need some common variables, a class with properties may be a good choice instead of a global:
class MyTest
{
protected $a;
public function __construct($a)
{
$this->a = $a;
}
public function head()
{
echo $this->a;
}
public function footer()
{
echo $this->a;
}
}
$a = 'localhost';
$obj = new MyTest($a);
If the variable is not going to change you could use define
Example:
define('FOOTER_CONTENT', 'Hello I\'m an awesome footer!');
function footer()
{
echo FOOTER_CONTENT;
}
If a variable is declared outside of a function its already in global scope. So there is no need to declare. But from where you calling this variable must have access to this variable. If you are calling from inside a function you have to use global keyword:
$variable = 5;
function name()
{
global $variable;
$value = $variable + 5;
return $value;
}
Using global keyword outside a function is not an error. If you want to include this file inside a function you can declare the variable as global.
// config.php
global $variable;
$variable = 5;
// other.php
function name()
{
require_once __DIR__ . '/config.php';
}
You can use $GLOBALS as well. It's a superglobal so it has access everywhere.
$GLOBALS['variable'] = 5;
function name()
{
echo $GLOBALS['variable'];
}
Depending on your choice you can choose either.
Add your variables in $GLOBALS super global array like
$GLOBALS['variable'] = 'localhost';
and use it globally as
echo $GLOBALS['variable']
or you can use constant which are accessible throughout the script
define('HOSTNAME', 'localhost');
usage for define (NOTE - without the dollar)
echo HOSTNAME;
This answer is very late but what I do is set a class that holds Booleans, arrays, and integer-initial values as global scope static variables. Any constant strings are defined as such.
define("myconstant", "value");
class globalVars {
static $a = false;
static $b = 0;
static $c = array('first' => 2, 'second' => 5);
}
function test($num) {
if (!globalVars::$a) {
$returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';
globalVars::$a = true;
} else {
$returnVal = 'I forgot';
}
return $returnVal;
}
echo test(9); ---> The value of 9 + 0 + 5 is 14.
echo "<br>";
echo globalVars::$a; ----> 1
The static keywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.
You can try the keyword use in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.
$foo = "New";
$closure = (function($bar) use ($foo) {
echo "$foo $bar";
})("York");
demo |
info
You can declare global variables as static attributes:
class global {
static $foo = "bar";
}
And you can use and modify it every where you like, like:
function echoFoo() {
echo global::$foo;
}
You answered this in the way you wrote the question - use 'define'. but once set, you can't change a define.
Alternatively, there are tricks with a constant in a class, such as class::constant that you can use. You can also make them variable by declaring static properties to the class, with functions to set the static property if you want to change it.
What if you make use of procedural function instead of variable and call them any where as you.
I usually make a collection of configuration values and put them inside a function with return statement. I just include that where I need to make use of global value and call particular function.
function host()
{
return "localhost";
}
$GLOBALS[] is the right solution, but since we're talking about alternatives, a function can also do this job easily:
function capital() {
return my_var() . ' is the capital of Italy';
}
function my_var() {
return 'Rome';
}
I am new to PHP.
I'm studying variables scopes.
A variable declared outside a function has a GLOBAL SCOPE and can only
be accessed outside a function.
A variable declared within a function has a LOCAL SCOPE and can only
be accessed within that function.
The global keyword is used to access a global variable from within a
function.
To do this, use the global keyword before the variables (inside the
function)
Normally, when a function is completed/executed, all of its variables
are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.
I need to declare variable within function to be global so I can get access to it from outside the function and to be static at the same time so I can keep the value of the variable after execution of the function and use it again.
I tried
global static $x;
but it doesn't work.
I need to know if I'm thinking in wrong way case I'm new to PHP.
<?php
$x = 5;
function myTest() {
echo "x is equal to".$GLOBALS['x']."";
$GLOBALS['x']++;
}
myTest();
myText();
?>
it executes only the first myTest().
and the second one display an error
Fatal error: Uncaught Error: Call to undefined function myText()
just declare it in global scope then use $GLOBALS[] array or global keyword to use that variable in a function. And as they hold the value even after function execution you don't need static keyword as well.
study $GLOBALS, Variable scope
you can use static or global to keep the value:
function doStuff() {
$x = null;
if ($x === null) {
$x = 'changed';
echo "changed.";
}
}
doStuff();
doStuff();
the result would be: changed.changed.
if you use:
function doStuff() {
static $x = null;
if ($x === null) {
$x = 'changed';
echo "changed.";
}
}
doStuff();
doStuff();
the result would be changed. because static keeps last value even if you call function in multi times
also global have the same result because of it's definition so you can also use:
global $x;
in the function and result would be same: changed.
You have typo problem in your code (second calling of your function):
function myTest() ....
Then you called it:
myTeXt();
Let us ignore the bad design and ponder the use of a variable which is global inside a function, but not global in the default namespace:
a();
function a() {
function b() {
global $x;
echo $x;
}
$x=10;
b();
}
The variable $x is not printed to stdout. However, if we declare global $x inside function a() then it is printed to stdout. Is there any way to define $x as global inside a() (such that it is available in the b() function) yet not in scope in the default namespace?
Edit: Assume that there is an arbitrarily large number of variables to pass, as such defining them with use() or as parameters is not practical.
Ignoring bad design or why you're not just passing this as a param, you can use a closure and an anonymous function, if you define the arguments before you define the function:
function a() {
$x = 10;
$b = function() use($x) {
echo $x; // 10
};
$b();
}
a();
echo $x; // Undefined variable
Say I have...
function one($x){
return $a + $x;
}
function two(){
$a = 5;
echo one(3);
}
Will this show the answer "8" or "3"? In other words, will function one get the value of $a or do I need to declare it global somewhere?
N.B. I haven't tried it yet, but I'm asking it here to understand WHY it acts one way or the other.
No function one does not know about $a. But this can be done.
$a = 5;
function one($x){
global $a;
return $a + $x;
}
function two(){
global $a;
$a = 5;
echo one(3);
}
Now two() would echo 8
Functions do not inherent scope from the function that calls them. (Nor do they inherit global variables by default - that's what the global keyword is for.)
Thus, $a will be completely undefined inside of one() and you'll get a notice about it.
For more details, see the Variable Scope page in the PHP manual.
You won't get 8 or 3. You'll get a Notice since $a has not been defined in the scope of the function one, and you attempt to read it:
PHP Notice: Undefined variable: a in - on line 3
PHP Stack trace:
PHP 1. {main}() -:0
PHP 2. two() -:11
PHP 3. one() -:8
If you to use a class as close as to your example, Notice no global usage, just assign your variables $this->* then there global scope within the class and its methods/functions you can also access them from outside of the class like $functions->a:
<?php
Class functions{
function one($x){
return $this->a + $x;
}
function two(){
$this->a = 5;
echo $this->one(3);
}
}
$functions = new functions();
$functions->two(); //8
echo $functions->a;//5
?>
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;
?>