変数(php)
静的変数(static変数)
通常、関数内で定義した変数は、その関数を呼び出すたびに初期化される。 「静的な変数」は定義すると、関数を複数回呼び出しても初期化されずに、その値は保持される。
<?php
function test1(){ $a = 0; return ++$a; }
function test2(){ static $a = 0; return ++$a; }
print test1(); //1 print test1(); //1 print test1(); //1
print test2(); //1 print test2(); //2 print test2(); //3 ?>
13-15行目は、関数が終了すると変数の値は破棄されるので何度呼んでも値は変わらない。 17-19行目は、関数が終了してもstatic変数は値を保持しているので呼び出すたびに値が増えている。
<?php function hoge() { static $count = 0; return ++$count; } echo hoge() ."\n"; echo hoge() ."\n"; echo hoge() ."\n"; echo hoge() ."\n"; ?>
実行結果
1 2 3
ローカル変数
インスタンス変数