PHP 

PHP has three different of variable scopes local, global and static.

Global variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:

<?php
$a = 5; // global scope variable

function myFunction() {
// You can’t use $a variable here its generate error
echo “Variable a inside function is: $a”;
}

myFunction();
echo “Variable a outside function is: $a”;
?>

Local variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:

<?php
function myFunction() {
$a = 5; // local variable
echo “Variable a inside function is: $a”;
}
myFunction();

// You can’t use a variable its generate error
echo “Variable a outside function is: $a”;
?>

Global Keyword: The global keyword is used to access a global variable from within a function. Such as-

<?php
$a = 2;$b = 5;

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

myFunction();
echo $b; // outputs 7
?>

PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.

<?php
$a = 2;
$b = 5;

function myFunction() {
$GLOBALS[‘b’] = $GLOBALS[‘a’] + $GLOBALS[‘b’];
}

myFunction();
echo $b; // output 7
?>

If you are define static keyword you can’t delete this you can override only. such as

<?php
function myFunction() {
static $a = 0;
echo $a;
$a++;
}

myFunction();//output 0
myFunction();//output 1
myFunction();//output 2
?>

 

 

News Reporter
IT Software and web development, Core PHP, JavaScript, JQuery, HTML, CSS, CakePHP, Angularjs, Codeigniter etc.

Leave a Reply

Your email address will not be published. Required fields are marked *

error: