PHP 関数でstatic変数を使用するサンプル

環境
PHP 8.1.2
Ubuntu 22.04.1 LTS

構文
static 変数
通常のローカル変数は関数が終了すると値は破棄されます。
通常のローカル関数が終了すると変数の値は破棄されるので何度呼んでも値は変わりません。
static変数は関数が終了しても変数の値を保持します。
static関数が終了してもstatic変数は値を保持しているので呼び出すたびに値が増えています。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<body>
<?php
function testA()
{
$n = 10;
return ++$n;
}
echo "通常のローカル変数";
echo "<pre>";
print testA();
echo "</pre>";
echo "<pre>";
print testA();
echo "</pre>";
echo "static変数";
function testB()
{
static $n = 5;
return ++$n;
}
echo "<pre>";
print testB();
echo "</pre>";
echo "<pre>";
print testB();
echo "</pre>";
?>
</body>
</html>
<!DOCTYPE html> <html> <body> <?php function testA() { $n = 10; return ++$n; } echo "通常のローカル変数"; echo "<pre>"; print testA(); echo "</pre>"; echo "<pre>"; print testA(); echo "</pre>"; echo "static変数"; function testB() { static $n = 5; return ++$n; } echo "<pre>"; print testB(); echo "</pre>"; echo "<pre>"; print testB(); echo "</pre>"; ?> </body> </html>
<!DOCTYPE html>
<html>
<body>

<?php
function testA()
{
    $n = 10;
    return ++$n;
}
echo "通常のローカル変数";
echo "<pre>";
print testA(); 
echo "</pre>";
echo "<pre>";
print testA(); 
echo "</pre>";

echo "static変数";
function testB()
{
    static $n = 5;
    return ++$n;
}
echo "<pre>";
print testB(); 
echo "</pre>";
echo "<pre>";
print testB(); 
echo "</pre>";

?> 

</body>
</html>

結果
通常のローカル変数
11
11
static変数
6
7

PHP

Posted by arkgame