PHP static変数

目次

static変数とは

2つの使い方があります。

1.関数内のstatic変数

  • 関数内でstaticをつけると、その変数は関数が呼ばれても値が保持され続けます。
  • 普通のローカル変数は関数を抜けると破棄されますが、staticをつけるとプログラム終了まで生き残ります。

2.クラスの staticプロパティ・メソッド

  • クラスのメンバにstatic を付けると、インスタンス化せずにクラスから直接利用できる共通の変数やメソッドになります。
  • 全インスタンスで共有されるので「クラス全体で1つだけの変数」を持ちたいときに使います。

関数でstatic変数を使用した場合

static 変数
  • static変数は関数が終了しても変数の値を保持します。
  • 通常のローカル変数は関数が終了すると値は破棄されます。
<?php
function test1()
{
    $a = 0;
    return ++$a;
}
print test1(); //1
print test1(); //1
print test1(); //1

function test2()
{
    static $a = 0;
    return ++$a;
}
print test2(); //1
print test2(); //2
print test2(); //3

4行目は、通常のローカル変数です。
7~9行目は、関数が終了すると変数の値は破棄されるので何度呼んでも値は変わりません。

13行目は、static変数です。
16~18行目は、関数が終了してもstatic変数は値を保持しているので呼び出すたびに値が増えています。

クラスをインスタンス化してstatic変数を使用した場合

クラスをインスタンス化してstatic変数を使用するサンプルです。

<?php
class Test1
{
    public function count()
    {
        $a = 0;
        ++$a;
        return $a;
    }
}
$t1 = new Test1();
$t2 = new Test1();
$t3 = new Test1();
print $t1->count(); //1
print $t2->count(); //1
print $t3->count(); //1

class Test2
{
    public function count()
    {
        static $a = 0;
        ++$a;
        return $a;
    }
}
$t1 = new Test2();
$t2 = new Test2();
$t3 = new Test2();
print $t1->count(); //1
print $t2->count(); //2
print $t3->count(); //3

6行目は、通常の変数です。
14~16行目は、同じ値が表示されます。

22行目は、static変数です。
30~32行目は、static変数のため呼び出すたびに値が増えています。
→(注意)インスタンスはそれぞれ別です。

staticメソッドでstatic変数を使う場合

staticメソッドでstatic変数を使うサンプルです。

<?php
class Test1
{
    public static function count1()
    {
        $a = 0;
        ++$a;
        return $a;
    }
    public static function count2()
    {
        static $a = 0;
        ++$a;
        return $a;
    }
}
print Test1::count1(); //1
print Test1::count1(); //1
print Test1::count1(); //1

print Test1::count2(); //1
print Test1::count2(); //2
print Test1::count2(); //3

6行目は、通常の変数です。
12行目は、static変数です。
17~19行目は、同じ値が表示されます。
21~23行目は、static変数のため呼び出すたびに値が増えています。

関連の記事

PHP ローカル変数とグローバル変数 (global)

△上に戻る