Php, invokeArgs: parameters changed, how to return them?

First of all, I want to check the function:

private function testMe (array &$output)
{
    $output['a'] = 3; // $$$$ $output gets changes
}

I made a small method to make it public, and call:

public static function makePublicAndCall ($objectInstance, $methodname)
{
    $ref = new ReflectionMethod (get_class($objectInstance), $methodname);
    $ref->setAccessible(true);

    $params = array();
    for ($i = 2+1; $i <= func_num_args(); $i++)
    {
        $params[] = func_get_arg($i-1);
    }
    $result = $ref->invokeArgs ($objectInstance, $params);
    for ($i = 2+1; $i <= func_num_args(); $i++)
    {
        // write back $$$$ here I would need something like "func_get_arg($i-1)"
    }
    return $result;
}

therefore, using it:

$output = array();
::makePublicAndCall ($object, 'testMe', $output);
// $output OMG output remains the same! It must not be empty but [a] => 3

see the problem? This method has 2 required parameters, and all the rest are optional (they go to the called method itself). But if these parameters are changed, they cannot be undone!

+4
source share
2 answers

For PHP 5.6 and higher

PHP 5.6 introduces variable arguments that can also take parameters by reference.

function makePublicAndCall ($objectInstance, $methodname, &...$args) { }

now just move the array $argsfilled with arguments with a link$objectInstance->$methodname

function makePublicAndCall ($objectInstance, $methodname, &...$args) {
    $ref = new ReflectionMethod (get_class($objectInstance), $methodname);
    $ref->setAccessible(true);
    return $ref->invokeArgs($objectInstance, $args);
}

makePublicAndCall($object, 'testMe', $output);

PHP 5.4 5.5

, , .

PHP 5.3

, .

function makePublicAndCall ($objectInstance, $methodname) {
    $ref = new ReflectionMethod (get_class($objectInstance), $methodname);
    $ref->setAccessible(true);
    return $ref->invokeArgs ($objectInstance, $args);
}
@makePublicAndCall($object, 'testMe', &$output); // note the & here...

, testMe, , , ; , ref, .

+2

, :

public static function makePublicAndCall ($objectInstance, $methodname, array &$params = array())
{
    $ref = new ReflectionMethod (get_class($objectInstance), $methodname);
    $ref->setAccessible(true);

    return $ref->invokeArgs ($objectInstance, array(&$params));
}

:

::makePublicAndCall ($object, 'testMe', $output);

EDIT: , , , :

public static function makeStaticMethodPublicAndCall ($className, $method, &$params1 = null, &$params2 = null, &$params3 = null, &$params4 = null)
{
    $className = new ReflectionClass($className);
    $method = $className->getMethod($method);
    $method->setAccessible(true);
    return $method->invokeArgs (null, array(&$params1, &$params2, &$params3, &$params4));
}

    .
    .
    .

::makeStaticMethodPublicAndCall ('MyClass', 'myMethod', $param1, $param2);
0

All Articles