PHPのグローバル変数についてまとめてみました。
概要
PHPは変数の範囲(スコープ)が関数の中に限定されます。
外の変数を中に適用する場合はグローバル変数として扱う必要があります。
$GLOBALSという連想配列に代入
$GLOBALSという特別な連想配列があります。これに代入すると関数の外でも中でもその値を取得できます。
$GLOBALS["apple"] = 111;
$GLOBALS["banana"] = 222;
function test1(){
return $GLOBALS["apple"];
}
$result=test1();
print $result;
// 111
$GLOBALS["banana"] = 222;
function test1(){
return $GLOBALS["apple"];
}
$result=test1();
print $result;
// 111
変数名がキーに
変数名をキーにすることもできます。
使い道がわかりません。
$carrot = 333;
function test2(){
return $GLOBALS["carrot"];
}
$result = test2();
print $result;
// 333
function test2(){
return $GLOBALS["carrot"];
}
$result = test2();
print $result;
// 333
関数の中でGLOBALSに代入
関数の外で那覇区、中で代入することもできます。
function test3(){
$GLOBALS["banana"] = 22222;
return $GLOBALS;
}
$result = test3();
print $GLOBALS["banana"];
// 22222
$GLOBALS["banana"] = 22222;
return $GLOBALS;
}
$result = test3();
print $GLOBALS["banana"];
// 22222
配列も代入可能
配列も使えます。
$GLOBALS["durians"] = array("good", "bad", "too bad");
function test4(){
return $GLOBALS["durians"][1];
}
$result = test4();
print $result;
// bad
function test4(){
return $GLOBALS["durians"][1];
}
$result = test4();
print $result;
// bad
$GLOBALSの中身
$GLOBALSはグローバル変数なので中身を全部出力してみます。
print_r($GLOBALS);
/*
Array
(
[GLOBALS] => Array
[apple] => 111
[banana] => 22222
[carrot] => 333
[durians] => Array
(
[0] => good
[1] => bad
[2] => too bad
)
)
*/
/*
Array
(
[GLOBALS] => Array
[apple] => 111
[banana] => 22222
[carrot] => 333
[durians] => Array
(
[0] => good
[1] => bad
[2] => too bad
)
)
*/
globalキーワード
グローバル変数を扱う別の手法があります。
globalキーワードを使います。
関数の中で「これはグローバル変数です」と宣言するような使い方です。
$apple=1111;
function test5(){
print $apple;
}
$result = test5();
// 印字されない(空文字が印字される)。
$apple = 1111;
function test6(){
global $apple; // ここがポイント!
print $apple;
}
$result = test6();
// 1111
function test5(){
print $apple;
}
$result = test5();
// 印字されない(空文字が印字される)。
$apple = 1111;
function test6(){
global $apple; // ここがポイント!
print $apple;
}
$result = test6();
// 1111
コメント