Home > Article > Backend Development > PHP function variable scope and function return value tutorial_PHP tutorial
In PHP, variables defined in a function, including parameters, cannot access variables outside the function, and by default, variables defined outside a function cannot access function variables.
In the PHP tutorial, variables defined in a function cannot be accessed, including parameters. Variables outside the function, and by default, variables defined outside a function cannot be accessed. Function variable.
See examples below
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
This returns the value of $b to 3. In php, global is a global variable, so this is the case. Now let’s look at the php variable reference example
function str_unite (&$string)
{
$string .= 'I also like blue.';
}
$str = 'Like red,';
str_unite ($str);
echo $str; // Output result: 'I like red and I also like blue.'
?>
, the above talks about the global variables of the function scope and the reference of the function , let’s look at the local variables of the function
$a = 1;
$b = 2;
function Sum($a,$b)
{
$b = $a + $b;echo $b;//3
}
Sum();//
echo $b;//2
?>
Please indicate the source when reprinting original tutorials on this site www.bkjia.com/phper/php.html