Behzadsh
Behzadsh

Reputation: 870

How to get caller method argument inside called method in php?

Let say, I have a class like this:

<?php

class ExampleClass {

    public function callerOne($arg1, $arg2) {
        return $this->calledMethod(function($arg1, $arg2) {
            // do something
        });
    }

    public function callerTwo($arg1) {
        return $this->calledMethod(function($arg1) {
            // do something
        });
    }

    protected function calledMethod(Closure $closure)
    {
        // How to access caller's arguments, like func_get_args()
        $args = get_caller_method_args();
        return call_user_func_array($closure, $args);
    }

}

In above example, method calledMethod wrap the passed closure in something, e.g. warp it between beginTransaction() and endTransaction(), but I need to access the caller method arguments.

I know that a possible solution would be using use statement when passing closure to calledMethod(), but it would be much easier on eye if what I wanted is possible.

How can I access to the caller's arguments, inside called method? Is that even possible?

Upvotes: 0

Views: 237

Answers (1)

Lukas Hajdu
Lukas Hajdu

Reputation: 804

I'm not sure if this helps in your case, but you can create ReflectionFunction and use ReflectionFunction::invokeArgs, which invokes the function and pass its arguments as array.

<?php

$closure = function () {
    echo 'Hello to: ' . implode(', ', func_get_args()) . PHP_EOL;
};

$reflection = new ReflectionFunction($closure);
// This will output: "Hello to: foo, bar, baz"
$reflection->invokeArgs(array('foo', 'bar', 'baz'));

Upvotes: 1

Related Questions