LoginSignup
6
6

More than 5 years have passed since last update.

コンストラクタがprivateなクラスを1行でテスト可能にする

Last updated at Posted at 2012-12-26

Singletonパターンで実装したクラスなど、__construct()privateprotected なクラスってそのままでは、インスタンス化できずテストが大変ですよね。

PHP5.4からは ReflectionClass でコンストラクタを使わないでインスタンスを作ることができるようになりました。

<?php

class Singleton
{
    private function __construct() {}
}

// $singleton = new Singleton(); // Fatal error: Call to private Singleton::__construct() from invalid context

$singleton = (new ReflectionClass('Singleton'))->newInstanceWithoutConstructor();

var_dump($singleton);

便利ですね!

追記 2013/12/19

@mpyw さんによるまとめ: private, protected なコンストラクタを外部からコールする方法

6
6
6

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
6
6