「static修飾子」付与 → クラスメソッド

PHP用語集

カテゴリー: クラスとオブジェクト  閲覧数:610 配信日:2016-12-09 09:28


クラスメソッド


クラスで定義されている関数の内、静的(static)なもの
・インスタンス化せずにアクセス可能

=静的メソッド
・インスタンス化せずにアクセス可能


クラスメソッド定義例


class Calculator{
 public static function addition($int1, $int2){
 }
 public static function substraction($int1, $int2){
 }
 public static function getAverage($intVals){
 }
}


クラスメソッド呼び出し例


Calculator::addition(10, 1);
Calculator::substraction(10, 1);
Calculator::getAverage($intVals);


クラスメソッドをメンバーとして持つクラス例


計算処理クラス

class Calculator{
   // 足し算
   public static function addition($int1, $int2){
       return $int1 + $int2;
   }

   // 引き算
   public static function substraction($int1, $int2){
       return $int1 - $int2;
   }

   // 平均値を求める
   public static function getAverage($intVals){
       if (false == is_array($intVals)) {
           return false;
       }
       $cnt = count($intVals);
       $total = 0;
       foreach ($intVals as $int) {
           $total += $int;
       }
       $average = $total / $cnt;
       return $average;
   }
}

$answer = Calculator::addition(10, 1);
var_dump($answer);

$answer = Calculator::substraction(10, 1);
var_dump($answer);

$intVals = array(1, 2, 3, 4, 5, 6, 7);
$answer = Calculator::getAverage($intVals);
var_dump($answer);


▼結果
int(11)
int(9)
int(4)




週間人気ページランキング / 4-17 → 4-23
順位 ページタイトル抜粋 アクセス数
1 PHP用語 8
2 「セキュリティ対策」で使用するPHP関数 2
2026/4/24 5:05 更新
指定期間人気ページランキング / 2020-5-28 → 2026-4-23
順位 ページタイトル抜粋 アクセス数
1 PHP用語 6729
2 ブラウザを閉じたらセッションデータはどうなるの? | セッション 2557
3 Parse error: syntax error, unexpected 'public' (T_PUBLIC) | Parse error(エラーメッセージ) 2515
4 ブラウザを閉じたらセッションデータはどうなるの? | セッション 1710
5 【テスト投稿】テスト | 1133
6 セッション管理が必要な理由は、HTTPプロトコルには状態を保持する機能がないため | セッション 1090
7 PHPで定数を定義する方法は2種類ある / 配列定数の定義 1067
8 Fatal error: Access level to ▲::$△ must be protected (as in class ●) or weaker | Fatal error(エラーメッセージ) 911
9 Fatal error: Uncaught Error: Call to a member function modify() on string | Fatal error(エラーメッセージ) 882
10 コード例 … 「例外処理」はネストすることができる 869
11 curl で Cookie を使用する 864
12 Fatal error: require_once(): Failed opening required 'PEAR.php' | Fatal error(エラーメッセージ) 863
13 Fatal error: Uncaught RuntimeException: SplFileObject::__construct(): failed to open stream: Permission denied in | Fatal error(エラーメッセージ) 751
14 定数 739
15 インターフェイス | クラスとオブジェクト 701
16 Fatal error: Uncaught HeadlessChromium\Exception\OperationTimedOut: Operation timed out (3sec) in | Fatal error(エラーメッセージ) 697
17 メンバー | クラスとオブジェクト 648
18 Warning: include() [function.include]: Failed opening '**.php' for inclusion (in | Warning(エラーメッセージ) 643
19 ( ! ) Fatal error: Uncaught PDOException: SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column | Fatal error(エラーメッセージ) 611
19 Warning: strlen() expects parameter 1 to be string, array given in ○○.php on line △△ | Warning(エラーメッセージ) 611
2026/4/24 5:05 更新