LoginSignup
1
1

More than 3 years have passed since last update.

staticキーワードをつけた関数内定義変数をunsetするとどうなるか

Posted at

結構面白い挙動になりました.

<?php

function func()
{
    static $x = 0;
    $x++;
    echo $x;
    unset($x);
    echo $x;
}

func();
func();
func();

image.png

4行目で static で宣言された $xくんは,8行目で unset() され,9行目で確かに未定義の状態となったことが確認できますが,次の関数呼び出しの際には元の値を保持したまま復活します.

面白いなと思ってPHPのマニュアルを見てみたら,マニュアルで紹介されている挙動でした (┐「ε:)ズコ-!

If a static variable is unset() inside of a function, unset() destroys the variable only in the context of the rest of a function. Following calls will restore the previous value of a variable.

destroyされたあと,restoreされるらしいです.すごいですね.

余談

staticキーワードを無駄に使ってメモリを無駄遣いするコードです.

<?php

function func()
{
    static $x;
    if (!isset($x)) {
        $x = 'func';
    }
    echo $x;
}

func();
func();
func();

1
1
0

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
1
1