23
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP7からはシングルトンの生成メソッドを2行で書ける

Last updated at Posted at 2016-11-28

PHP7未満ではシングルトンの生成メソッドはこんな感じだったと思います。staticで静的変数を定義し、それがNULLかどうかのif節を書きといった具合に。

<?php

function getInstanceOldStyle()
{
	static $instance;
	if ($instance === null) {
		$instance = new stdClass();
	}
	return $instance;
}

assert(getInstanceOldStyle() === getInstanceOldStyle());

PHP7からはnull 合体演算子 (??) が追加されたので、もっとシンプルに書くことができそうです。

function getInstance()
{
	static $instance;
	return $instance ?? $instance = new stdClass();
}

assert(getInstance() === getInstance());

なおクラスのstaticキーワードを使うならこんな感じでしょうか。

class Singleton
{
	private static $instance;
	
	public static function getInstance()
	{
		return self::$instance ?? self::$instance = new self();
	}
}

assert(Singleton::getInstance() === Singleton::getInstance());
23
20
1

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
23
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?