1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you kindly @jbafford. I'll be trying this out shortly.
Just tested it out, and it's everything you said it was and more, @jbafford. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.