PHPでの、メソッド内の静的変数のスコープ(static)
ベーシックな事ですが、PHP の静的変数のスコープ(?)に関して気づいた事を、忘れそうなのでメモ。
以下のコードについて:
class Counter { function print_count() { static $counter; echo ++$counter . "<br />"; } } class CounterA extends Counter { } class CounterB extends Counter { } $A = new CounterA; $B = new CounterB; $A->print_count(); $A->print_count(); echo "----<br>"; $B->print_count(); $B->print_count(); $B->print_count(); echo "----<br>"; CounterA::print_count(); CounterB::print_count();
出力結果は下記の通り:
1 2 ---- 1 2 3 ---- 3 4
結論:
クラスのメソッド内の静的変数のスコープは、オブジェクト毎では無く、クラス毎になるみたい。
これまで、微妙〜に認識を間違えていて、キャッシュは何でも、オブジェクト変数に入れていたけれど、そうでも無くても良さそうです。