LoginSignup
26
24

More than 5 years have passed since last update.

PHPの関数内static変数

Last updated at Posted at 2014-03-09

PHPは、関数の中でstatic変数を宣言すると、その関数が初めて呼ばれた時にのみ初期化をし、それ以降は何度呼ばれても初期化処理をスキップしつつ、値を保持する機能があります。

function staticVar() {
    static $var = 0;
    $var++;
    var_dump($var);
}

staticVar(); // 1
staticVar(); // 2
staticVar(); // 3

こんな感じで。
クラス化してメソッドにしても同様みたいです。
今のところ、良い使いドコロが思いつきませんけど・・・。

26
24
4

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
26
24