|
比如下面這樣:
復(fù)制代碼 代碼如下:
$test = 123;
abc(); //這里什么都不輸出,因?yàn)樵L問不到$test變量
function abc(){
echo($test);
}$test = 123;
abc(); //這里什么都不輸出,因?yàn)樵L問不到$test變量
function abc(){
echo($test);
}
如果,你想在函數(shù)內(nèi)部訪問外部變量,你需要這樣:
復(fù)制代碼 代碼如下:
$test = 123;
abc(); //輸出123
function abc(){
global $test;
echo($test);
}$test = 123;
abc(); //輸出123
function abc(){
global $test;
echo($test);
}
但如果我們?cè)诤瘮?shù)中定義全局變量呢,像下面這樣:
復(fù)制代碼 代碼如下:
function abc(){
global $test;
$test = 123;
}
abc();
echo($test); //輸出123function abc(){
global $test;
$test = 123;
}
abc();
echo($test);
//輸出123通過這種方式,我們可以在外部訪問到函數(shù)內(nèi)部定義的變量
在用戶自定義函數(shù)中,一個(gè)局部函數(shù)范圍將被引入。任何用于函數(shù)內(nèi)部的變量按缺省情況將被限制在局部函數(shù)范圍內(nèi)(包括include 和 require 導(dǎo)入的文件內(nèi)的變量)!
解釋:A.php文件的內(nèi)Test_Global是定義好的第三方函數(shù),該函數(shù)用include導(dǎo)入了B.php文件內(nèi)的$a的global全局變量,所以$a被限制在Test_Global局部函數(shù)范圍內(nèi),所以B.php文件內(nèi)的$a的作用范圍都在Test_Global內(nèi),而不是作用了整個(gè)A.php內(nèi)….
解決方案:
1. 沖出局部函數(shù)
//A.php 文件
復(fù)制代碼 代碼如下:
<?php
function Test_Global()
{
Test();
}
include 'B.php'; //將include 從局部Test_Global函數(shù)中移出
$a = 0 ;
Test_Global();
echo $a;
?>
//B.php 文件
<?php
function Test()
{
global $a;
$a =1;
}
?>
2.優(yōu)秀的訪問器
復(fù)制代碼 代碼如下:
//A.php 文件
<?php
include 'B.php';
$a =0;
Set_Global($a);
echo $a;
?>
//B.php 文件
<?php
function Set_Global(&$var)
{
$var=1;
}
?>
php技術(shù):PHP Global定義全局變量使用說明,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。