![](/img/trans.png)
[英]PHP global variable is null inside a function, but is not null outside it
[英]global inside and outside a function in PHP?
我通常會這樣運行代碼:
$ZANE_REGISTER_RULES='this wont print';
myTest();
function myTest()
{
**global $ZANE_REGISTER_RULES**;
$ZANE_REGISTER_RULES='this will actually print';
}
echo $ZANE_REGISTER_RULES; //will print "this will actually print"
但是有時(例如:如果我將其放在phpBB頁面中)將無法正常工作(回聲顯示“ this not print”),除非我也第一次聲明了全局變量:
**global $ZANE_REGISTER_RULES**;
$ZANE_REGISTER_RULES='my rulessssssssssssssss';
myTest();
function myTest()
{
**global $ZANE_REGISTER_RULES**;
$ZANE_REGISTER_RULES='funziona';
}
echo $ZANE_REGISTER_RULES; //will print "this will actually print"
我很確定第一種方法是正確的,而第二種方法則沒有任何意義,但是第二種方法有效,第一種方法則無效。
請不要浪費時間回答“全局編程不好”,因為這不是手頭的問題,也不是“為什么要這樣做?” 因為這顯然是一個例子。
發生這種情況的原因只有一個:第二個示例中的代碼是在函數上下文中編譯的。 這就是$ZANE_REGISTER_RULES
默認具有本地范圍的原因。
如果源文件中沒有包含代碼本身的封閉功能,則表示該文件被函數上下文中的其他文件包含,例如:
var_access.php
echo "Hello ".$name."\n";
echo "Hello ".$_GLOBALS['name']."\n";
test_1.php
// Here var_access.php is included in the global context
$name = 'world';
include('var_access.php'); // Prints "Hello world" twice
test_2.php
// Here var_access.php is included in a function context
$name = 'world';
function func() {
$name = 'function world';
include('var_access.php'); // Prints "Hello world" and "Hello function world"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.