PHP クラスをインスタンス化してstatic変数を使用するサンプル
環境
PHP 8.1.2
Ubuntu 22.04.1 LTS
構文
通常のローカル変数は関数が終了すると値は破棄されます。
通常のローカル関数が終了すると変数の値は破棄されるので何度呼んでも値は変わりません。
static 変数
static関数が終了してもstatic変数は値を保持しているので呼び出すたびに値が増えています。
書式
class クラス名
public function 関数名() {
static $変数名 = 値:
処理コード
}
class クラス名
public function 関数名() {
static $変数名 = 値:
処理コード
}
class クラス名 public function 関数名() { static $変数名 = 値: 処理コード }
使用例
<!DOCTYPE html>
<html>
<body>
<?php
class FunA
{
public function count()
{
echo "通常の変数を使用する\n";
$a = 10;
++$a;
return $a;
}
}
$t1 = new FunA();
$t2 = new FunA();
echo "<pre>";
print $t1->count();
echo "</pre>";
echo "<pre>";
print $t2->count();
echo "</pre>";
class FunB
{
public function count()
{
echo "static変数を使用する\n ";
static $a = 20;
++$a;
return $a;
}
}
$t1 = new FunB();
$t2 = new FunB();
echo "<pre>";
print $t1->count();
echo "</pre>";
echo "<pre>";
print $t2->count();
echo "</pre>";
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
class FunA
{
public function count()
{
echo "通常の変数を使用する\n";
$a = 10;
++$a;
return $a;
}
}
$t1 = new FunA();
$t2 = new FunA();
echo "<pre>";
print $t1->count();
echo "</pre>";
echo "<pre>";
print $t2->count();
echo "</pre>";
class FunB
{
public function count()
{
echo "static変数を使用する\n ";
static $a = 20;
++$a;
return $a;
}
}
$t1 = new FunB();
$t2 = new FunB();
echo "<pre>";
print $t1->count();
echo "</pre>";
echo "<pre>";
print $t2->count();
echo "</pre>";
?>
</body>
</html>
<!DOCTYPE html> <html> <body> <?php class FunA { public function count() { echo "通常の変数を使用する\n"; $a = 10; ++$a; return $a; } } $t1 = new FunA(); $t2 = new FunA(); echo "<pre>"; print $t1->count(); echo "</pre>"; echo "<pre>"; print $t2->count(); echo "</pre>"; class FunB { public function count() { echo "static変数を使用する\n "; static $a = 20; ++$a; return $a; } } $t1 = new FunB(); $t2 = new FunB(); echo "<pre>"; print $t1->count(); echo "</pre>"; echo "<pre>"; print $t2->count(); echo "</pre>"; ?> </body> </html>
実行結果
通常の変数を使用する
11
通常の変数を使用する
11
static変数を使用する
21
static変数を使用する
22
通常の変数を使用する
11
通常の変数を使用する
11
static変数を使用する
21
static変数を使用する
22
通常の変数を使用する 11 通常の変数を使用する 11 static変数を使用する 21 static変数を使用する 22