NotoriousWebmaster
NotoriousWebmaster

Reputation: 3568

Getting a Calling Function's Arguments in PHP

I'm working on a logging class, and I'd like to add a convenience function which would log the arguments of the function from which it is called. A little convoluted, so here's some code:

function MyFunc($arg1, $arg2) {
   global $oLog;

   $oLog->logArgs();
}

So, I can get the name of the calling function (MyFunc) using debug_backtrace(). I'd be interested in getting the names and values of the arguments, preferably without having to add func_get_args() in the call to logArgs().

I know it's a tall order, but PHP continues to surprise me, so I'm putting it out there, just in case.

Thanks.

Upvotes: 1

Views: 49

Answers (1)

jbafford
jbafford

Reputation: 5668

You can do this with reflection:

function logger()
{
    $bt = debug_backtrace();

    $previous = $bt[1];

    if(empty($previous['class'])) {
        $fn = new ReflectionFunction($previous['function']);
    } else {
        $class = new ReflectionClass($previous['class']);
        $fn = $class->getMethod($previous['function']);
    }

    $parameters = $fn->getParameters();
    //Get a parameter name with $parameters[$paramNum]->getName()
    //Get the value from $previous['args'][$paramNum]
}

This particular implementation won't work with closures, but it will work with both global functions and class methods.

Upvotes: 1

Related Questions