我是PHP新手。 我正在研究变量范围。PHP变量全局和静态
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function)
Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.
我需要函数内声明的变量是全球性的,所以我可以从函数外部访问它,并在同一时间静态的,所以我可以在功能执行后保留变量的值并再次使用它。 我试图
global static $x;
,但它不工作。
我需要知道我是否以错误的方式思考我是否是PHP新手。
<?php
$x = 5;
function myTest() {
echo "x is equal to".$GLOBALS['x']."";
$GLOBALS['x']++;
}
myTest();
myText();
?>
它只执行第一个myTest()。 ,第二个显示一个错误 致命错误:未捕获的错误:调用未定义会将myText函数()
为什么你需要在函数内全局声明变量?你不能在全球范围内宣布它吗? –
全局变量在函数执行后仍然存在,那么为什么你需要它们是静态的呢? –
如果我有很多函数,比如20,30个函数,那么在函数之外声明变量将是一个糟糕的解决方案,这将是一个大混乱! –