1
0

More than 1 year has passed since last update.

【PHPUnit】ReflectionClassで参照渡しのメソッドを実行

Last updated at Posted at 2022-11-04

実行環境

  • PHP8

内容

PHPUnitでprivateやprotectedのメソッドをテストしたい時に、ReflectionClassクラスを使って実行する。
この時に、実行するメソッドの引数が参照渡しになっている場合、エラーになってしまったので解決方法をメモしておきます。

失敗例

<?php

class Hello {
    private function sayWord(&$word) {
        echo $word;
    }
}

$param = 'Hello';

$object = new Hello();

$reflectionMethod = new ReflectionMethod($object, 'sayWord');

$reflectionMethod->setAccessible(true);

$reflectionMethod->invokeArgs($object, [$param]);

実行結果

Warningエラーが発生する。

Warning: Hello::sayWord(): Argument #1 ($word) must be passed by reference, value given in test.php 17
Hello

解決方法

呼び出す際に、引数にも「&」をつける必要がある。

$reflectionMethod->invokeArgs($object, [&$param]);

実行結果

Warningが解消されて実行される。

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