Home > Article > Backend Development > PHP function variable scope and function return value tutorial
In PHP, regarding variables defined in a function, variables outside the function, including parameters, cannot be accessed, and by default, variables defined outside a function cannot access function variables.
Look at the example below, The code is as follows:
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $ b;
}
Sum();
echo $b;
?>
The value of $b returned is 3. In php, global is a global variable, so this is the case, so let’s do it now Look at the php variable reference example, the code is as follows:
function str_unite (&$string)
{
$string .= 'Also like blue.';
}
$str = ' Like red, ';
str_unite ($str);
echo $str; // Output result: 'Like red, also like blue.'
?>
The above is about the scope of the function References to global variables and functions. Let’s look at the local variables of a function. The code is as follows:
$a = 1;
$b = 2;
function Sum($a,$b)
{//Open source code phpfensi.com
$b = $a + $b;
echo $b;//3
}
Sum();//
echo $b;/ /2
?>