LoginSignup
0
1

More than 1 year has passed since last update.

PHP(Laravel)環境でstaticおじさんにならない心構え-staticの使いどころ編

Last updated at Posted at 2022-12-28

追記

なし

はじめに

いろんな記事を見た結果、圧倒的私流結論をまとめると下記以外はstaticはやめとけデス

あるときstaticの使い方に悩みました。いつ使うんだこれは、と。
「static 使いどころ PHP」みたいに検索しても、「クラスのインスタンスを生成することなしに利用できるプロパティやメソッドのこと」とかそんなことしか書いてなかったです。(私感)

聞きたいのはそんなことじゃない。
いつ、どんな時に使うんだよ。

となったので、下記3つの時さえ注意してればOKかなと。
ワタシと同じ気持ちの人はぜひ参考にしてください。私の解釈なのであくまでご参考に。(※ここ違うんじゃないみたいなのは随時受け付けてますので優しくお願いします。)

staticの使いどころ

【其の一】 singleton patternとか

singleton patternとはインスタンスが一つしか存在しないことを保証するパターン。
簡単にコードを記述してみると下記みたいな感じ。
Logger::getInstance()等もこれにあたりますね。

route.php
Route::get('singleton/sample', 'App\Lib\SingletonSampleCall@main');
SingletonSampleCall.php
<?php

namespace App\Lib;

/**
 * SingletonSampleCall Class
 */
class SingletonSampleCall
{
    public function main()
    {
        $singletonSample1 = SingletonSample::getInstance();
        $singletonSample2 = SingletonSample::getInstance();
        
        if ($singletonSample1 === $singletonSample2) {
            Log::debug('singletonSample1 is equal to singletonSample2 .');
        } else {
            Log::debug('singletonSample1 is not equal to singletonSample2 .');
        }
        
        $errorCase = new SingletonSample();
    }
}

SingletonSample.php
<?php

namespace App\Lib;

/**
 * SingletonSample Class
 */
class SingletonSample
{
    private static $singletonSample;

    private function __construct()
    {
        Log::debug('created instance');
    }

    public static function getInstance()
    {
        // $singletonSampleプロパティにinstanceがセットされていなければ実行
        if (!isset(self::$singletonSample)) {
            self::$singletonSample = new SingletonSample();    
        }

        return self::$singletonSample;
    }
}

上記コードを実行したログが以下。
「singletonSample1 is equal to singletonSample2 .」なので作成されたインスタンスが同一ということがわかります。
また、SingletonSampleCallから直接インスタンスを作成しようとするとconstructがprivateの為エラーが表示されます。

local.DEBUG: created instance  
local.DEBUG: singletonSample1 is equal to singletonSample2 .  
local.ERROR: Call to private App\Lib\SingletonSample::__construct() from scope App\Lib\SingletonSampleCall

【其の二】 factory methodとか

MyClass::factory()等のそのクラスのインスタンスを作るためのものです。

【其の三】 ヘルパー関数とか

「Arr::add」や「Str::random」などですね。
通常の関数ではなくクラスのstatic functionとして実行するものたちです。

まとめ

とりあえず上記以外のメソッドは、基本的にはstatic使わずにinstanceで書いておこう。
そうすればstaticおじさんにはならないはず。
そんな感じ。

参考リンク

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