LoginSignup
0
0

More than 5 years have passed since last update.

PHPで private static なプロパティに値をセットする方法

Last updated at Posted at 2018-10-17

テストのために private staticなプロパティを書き換えたくて調べました。

具体的にやりたかったのは CakePHP2 の ModelのDB接続を提供している ConnectionMangerの _dataSourcesプロパティにモックのDBを突っ込みたかったんですね。

通常のインスタンスのプロパティなら

$property = new ReflectionProperty($insatnce, '__privateProperty');
$property->setAccessible(true);
$property->setValue('セットしたい値');

なんだけど、クラスのstaticプロパティだとこうはいかないので、一旦ReflectionClass経由すればよいようです。

下記のようにすると private static プロパティもセットできました。

$class = new ReflectionClass(ConnectionManager::CLASS);
$property = $class->getProperty('_dataSources');
$property->setAccessible(true);
$property->setValue(['test' => $db]);
// 追記 これで差し替えちゃうと他のテストが失敗するので差し替え前にバックアップしてテスト後に元に戻しましょう^^;

まぁ、こんなややこしいことしないとテストできないようなコードになってるのがダメだとはおもうんですが、いろんな制約のなかでこんなしてテストすることもあるのよね…^^;

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