我正在测试一个变量的功能$年龄=30。我把变量放在函数体之外:输出是可以的,但当我把变量放到函数的echo之前时。。以及回声之后。。抛出错误。。为什么?我想了解错误机制。第一个例子:
<?php
function birthday(){
static $age = 0;
$age = $age + 1;
$age = 30;
echo "Birthday number $age <br/>";
}
birthday();
birthday();
birthday();
echo "Age: $age<br/>";
?>
Output:Birthday number 30
Birthday number 30
Birthday number 30
Notice: Undefined variable: age in C:'xampp'htdocs'series'exercitii_php'variabila_statica.php on line 18
Age:
Why?
second example:
<?php
function birthday(){
static $age = 0;
$age = $age + 1;
echo "Birthday number $age <br/>";
$age = 30;
}
birthday();
birthday();
birthday();
echo "Age: $age<br/>";
?>
Output: Birthday number 1
Birthday number 31
Birthday number 31
Notice: Undefined variable: age in C:'xampp'htdocs'series'exercitii_php'variabila_statica.php on line 18
Age:
请给我你的解释,这样我才能理解。
我想你想要这样的东西:
function birthday() {
static $age = null;
if (empty($age)) {
$age = 30;
} else {
$age = $age + 1;
}
echo "Birthday number $age <br/>";
}
birthday();
birthday();
birthday();
注意:不能在全局范围内访问$age
,因为它在函数范围内。
如果你想让它用作global
,那么你不能把它用作静态,但我认为这是最糟糕的选择:
global $age;
function birthday() {
global $age;
if (empty($age)) {
$age = 30;
} else {
$age = $age + 1;
}
echo "Birthday number $age <br/>";
}
birthday();
birthday();
birthday();
echo $age;
您的$age
变量是birthday
方法/函数的本地变量,因此不能在该方法的范围之外使用。为了在脚本中的任何地方使用它,您要么必须使它成为脚本的全局,要么将它放在一个类中,使用getter/setter,或者将它公开(但这真的很糟糕!)。
有关变量范围的更多信息,请点击此处:http://php.net/manual/en/language.variables.scope.php