Tuesday, July 15, 2014

Global variables in PHP

Basic Concept
By declaring a variable as Global(Common), we can access it any where of the program.

In C or C++
Here they don't use any special keyword to denote the variable as global. Say for example you defined  or declared a variable with a name in top of the program, now if you use the same name in any where of your program even inside a function, it will denote that as global variable.

Example 1:
#include<stdio.h>
// Global variables
int A=5;
int B=7;

int Add()
{
return A + B;
}

void main()
{
int answer; // Local variable
answer = Add();
printf("%d\n",answer);   // Output: 12
}

In PHP
Here to use global variable inside a function, first we have to declare it as "global".

Example 2:
<?php
$a = 1;
$b = 2;

function Sum()
{
    global $a, $b;
    $b = $a + $b;
}

Sum();
echo $b;   // Output: 3
?>

And one more way is we can use a super global valiable called $GLOBALS, intead of the keyword global.

Example 3:
<?php
$a = 1;
$b = 2;

function Sum()
{
    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}

Sum();
echo $b;   // Output: 3
?>

We could not directly declare a class property as global variable. But we can get global variable under a function inside a class. So it can done by assigning global variable value on a property inside the constructor function.

Example 4:
<?php
$a=5;
class A
{
// private global $a; This is wrong statement. It will not going work.
        privare $a;

function __construct()
{
global $a;
$this->a=$a;
}

 function fun1()
{
global $a;
echo 'value of "a" inside class A is: '.$a;
}
}

$obj=new A();
$obj->fun1();
?>

References:
http://php.net/manual/en/language.variables.scope.php
http://www.codingunit.com/c-tutorial-functions-and-global-local-variables

No comments:

Post a Comment

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS&l...