我是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個函數,那麼在函數之外聲明變量將是一個糟糕的解決方案,這將是一個大混亂! –