The range of variables

The range of variables

When you use the functions and classes there is a problem range of variables. This problem applies to most programming languages. Variables are usually available only in the range in which they are declared. For a range understand range master (piece of code that does not belong to any function or class), classes and functions.

Example

<?php

$a = 24;

function aaa  ()
{

echo $a;

}

aaa();

?>

Although the $a variable is declared in advance, it does not appear, because the variable $a is not available within the function. Access to global variables can be obtained in 2 ways. First, you tell PHP that the variable is to be charged with a range of main using the global statement.

Example
<?php

$a = 26;

function aaa ()
{
global $a;

echo $a;

}

aaa ();

?>

In this example displays the correct value of $ a. There is also a second method of getting into the global variables. In each position of the code is available associative array $GLOBALS, where the keys are the names of variables available within the main.
There is another aspect concerning the range of variables: the static variables.
Example
<?php

function aaa()
{

$a = 0;

echo $a;

$a ++;
}

aaa ();
aaa ();
aaa ();

?>

The above example is basically pointless – every time displayed will be the value 0, because every call to the $ a variable will be again initiated a value of 0 and after displaying and increment of this variable will be destroyed (all variables initialized in the function besides static are destroyed after the functions).
Example
<?php

function aaa ()
{

static $a = 0;

echo $a;

$a ++;

}

aaa ();
aaa ();
aaa ();

?>

 

However, in this example displays the values 0, 1 and 2. This is because even though the variable is initialized to a value of 0, thanks to instructions static happens it only once, and that after completion of the function of this variable is not destroyed.
In PHP 4.1.0 have been introduced so-called superglobal arrays. They are created by PHP – you can not itself create such arrays. They contain data passed to PHP methods GET, POST, information submitted files, data and session cookies –  $ _GET, $ _POST, $ _FILES, $ _COOKIE, $ _ SESSION. They replace $ HTTP _ * _ VARS, which, due to compatibility are still present. The difference between the superglobal arrays and those used previously is that superglobal arrays are available anywhere in the code, without the need for a global statement.

Cookies help us deliver our services. By using our services, you agree to our use of cookies. More Info | Close