Home  >  Article  >  Backend Development  >  PHP function variable scope and function return value tutorial_PHP tutorial

PHP function variable scope and function return value tutorial_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 11:01:191022browse

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


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/445451.htmlTechArticleIn 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 be accessed...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn