At the moment, we know a few different rules:
- When a function is defined, the variable that is enclosed in parentheses is a formal parameter (formal parameter), which has no relation to a variable outside the body of the function. It's just inside the function.
- Variables declared within a function are also irrelevant to variables outside the function.
However, we will encounter such a situation in the actual processing situation:
- I want to define variables in the function body for external use
- I want to get the variables outside the function body to use in the body.
1. Read external variables via $globlas
<?php
$one = 10;
function demo(){
$two = 100;
$result = $two + $GLOBALS[‘one‘];
return $result;
}
//你会发现结果变成了110
echo demo();
?>
in the example above : we get the function body to use the variable outside the function body through $globals. Therefore, a variable outside the function cannot be used within the function body.
2. Modify the external variables within the function by $globlas
<?php
$pangsir = ‘我是一个兵,来自老百姓‘;
function test(){
echo ‘执行了函数test哟<br />‘;
//调用test()函数,将通过$GLOBALS[‘pangsir‘],把$pangsir 的值改变掉
$GLOBALS[‘pangsir‘] = ‘帮助别人很快乐‘;
}
test();
//发现是不是输出的值变了呀?
echo $pangsir;
?>
By the example above: we found that through GLOBALS [ PaNg sI R- ],put G l O B A L S [ p a n G s i r ] , put The value of the Pangsir is changed, so the value changes when the last output $pangsir.
3. Create a global variable within a function by $globlas
<?php
function hello(){
$GLOBALS[‘que‘] = ‘提神喝茶更好哟‘;
echo ‘你调了一下函数hello<br />‘;
}
hello();
echo $que;
?>
From for notes (Wiz)
Front-end PHP entry -013-variable scope