Thursday, 20 November 2014

PHP Variables

PHP Variables
A variable starts with the $ sign, followed by the name of the variable like $abc.
A variable name must begin with a letter or the underscore character. Some valid names are $_abc, $a12 etc.
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
<?php
$x=3;
$y=4;
$z=$x+$y;
echo $z;
?>

Local Scope
If we declare a variable inside a function, then its scope is local and it can only be accessed with in the function. Local variables are deleted as soon as the function is executed.
<?php
$var=5; // global scope
function test()
{
echo $var; // local scope
}
test();
?>

Global ScopeIf the variable is declared outside of a function then its scope is global and if we want to access a global variable inside a function, we need to useglobalkeyword.
<?php
$a=5; // global scope
$b=1; // global scope
function test()
{
global $a,$b;
$b=$a+$b;
}
echo $b; // output is 1
test();
echo $b; // output is 6
?>

Static ScopeIf you want a local variable not to be deleted after the function is executed, you can declare it as static. The static variable is however local to the function only and can’t be referenced in other functions. We can use static variable to count the number of times a function is executed.
<?php
function test()
{
static $x=0;
echo $x;
$x++;
}
function test1()
{
echo $x; //this won't print anything because $x is static but local to test()
$x++;
}
test();
test1();
test();
?>

No comments:

Post a Comment