lundi 17 octobre 2016

PHP Reflection Method > Returning Reference Impossible

I needed to test if my abstract class can correctly return a reference to an internal array from a protected method. The only way to test a protected method is via a reflection. However, it doesn't seem to be possible to have a reference returned by ReflectionMethod::invokeArgs(). Or am I doing something wrong here?

class A
{
   protected $items;

    protected function &_getItemStorage()
    {
        return $this->items;
    }
}

function &reflectionInvokeByRef($object, $method, $args = array())
{
    $reflection = new \ReflectionMethod($object, $method);
    $reflection->setAccessible(true);
    $result = &$reflection->invokeArgs($object, $args);

    return $result;
}

$a = new A();
$items = &reflectionInvokeByRef($a, '_getItemStorage');

This results in the following error: Only variables should be assigned by reference
On line: $result = &$reflection->invokeArgs($object, $args);

This error is normally thrown when trying to assign a return value of a function by reference, whereas the function is not declared as returning by reference. Makes my functionality un-testable using any known method.





Aucun commentaire:

Enregistrer un commentaire