LoginSignup
0

More than 5 years have passed since last update.

ローカル変数とグローバル変数

Last updated at Posted at 2018-08-08

変数のスコープ

変数には使える範囲(スコープ)が存在する。例えば、

$num = 200;

function total($var){
 return $result = $var*1.08;
}

echo total($num);
echo $result;

最後の$resultはエラー。$resultは関数の中だけで有効なローカル変数だから!
逆に関数の外で作られた変数はグローバル変数といって、どこでも共通で使える。ただし、

$num = 200;

function total($var){
 echo $num;
 return $result = $var*1.08;
}

echo total($num);
echo $num;

こういうときのfunction内の$numは何も表示されない。関数内で使えるローカル変数として扱われているから。
グローバル変数を関数内で使える方法もちゃんとあって、

$num = 200;

function total($var){
 global $num;
 echo $num;
 return $result = $var*1.08;
}

echo total($num);
echo $result;

こうすればOK。

ウェブカツ!!

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0