Friday, February 14, 2014

Variables Part 2

In the last post, I talked about how to declare a variable in PHP. In this post, I will cover the differences between the three levels of variables in PHP.

In PHP, a given variable will exist on one of three levels:

1. Global
2. Local non static
3. Local static

1. Global Variables
If you have had experience with other programming languages before, then this might seem a bit familiar.
A global Variable is a variable that can be accesses and/or changed from every function in a particular PHP class.These variables are helpful if you need to reference the same stored value for a variety of different processes.

What is a bit different in PHP , is that Global Variables are only distinguished by their declaration location in the program. Unlike in many other languages, there is no "Global" modifier.
To ensure a variable is declared as Global, it must be declared before and outside of any functions in the program.

<?php

$X=the global variable
function LearnPHP1()
{

echo "I can see " + $X;

}


function LearnPHP2()
{
echo "I can also see " + $X;
}

>


2.Non-Static Local Variables
 A Local non-static variable have two key properties that distinguish it: itcan only be accessed and modified within the function it is defined, and any changes made to the value of the variable are discarded after the 
function  it is in  has finished executing.

A variable is declared as local if it is declared within a specific function. All local variables are considered to be non-static by default-  so it is not necessary to specify it.

<?php

function LearnPHP()
{
$X=0;
echo $X;
$X++;
}


LearnPHP();
LearnPHP();

>


Even though LearnPHP is called twice, the changes to $X from the first call are not carried over to the second call.

At the end of the second call to LearnPHP();, $X only equals 1.



3. Static Local Variables
A local static variable can only be accessed within the function it is defined, but  changes made to the value of the variable are not discarded- all changes to it carry over for the next times the function is called.

A local variable can be declared as static with the "static" modifier upon deceleration

Example:


<?php

function LearnPHP()
{
static $X=0;
echo $x;
$x++;
}


LearnPHP();
LearnPHP();

>

Since $X is declared as static, the changes made to $X in the first call of LearnPHP are carried into the second call. At the end of the second call, the value of $X is 2.


No comments:

Post a Comment