Local Variables in PHP

Lecture



A variable declared inside a user-defined function is considered local; in other words, it can only be referenced in this function. Any assignment outside the function will use a completely different variable that has nothing in common (except the name) with the variable declared inside the function. When exiting a user function in which a local variable was declared, this variable and its value are destroyed.

The main advantage of local variables is the absence of unforeseen side effects associated with accidental or intentional modification of a global variable. Consider the following example:

<?php
$a = 1; /* глобальная область видимости */

function Test()
{
echo $a; /* ссылка на переменную локальной области видимости */
}

Test();
?>

This script does not generate any output, because the echo expression points to the local variable $ a , and within the local scope it has not been assigned a value.

The approach to scope in PHP is different from the C language in that global variables in C are automatically accessible to functions, unless they have been overwritten by a local definition. In PHP, if a global variable is used inside a function, it must be declared global inside it:

<?php
$a = 1; /* глобальная область видимости */

function Test()
{
global $a; /* Объявляем переменную $a глобальной */
echo $a; /* ссылка на переменную локальной области видимости */
}

Test();
?>

As a result of the script operation, the test () function will return "1", since we have declared the variable $ a global , that is, made the variable $ a accessible to the entire program (script).

created: 2016-01-25
updated: 2021-03-13
132386



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)