Search code examples
phpvariable-variables

get_func_argNames and variable variables


I'm writing a method to generate detailed data for logging functions and arguments in debug mode. I previously reproduced the same code in multiple places (bad), but it works just fine (good):

function validate_date($date)
{

    if ($condition)
    {
        $php_function       = __FUNCTION__;
        $php_function_args  = implode(', ',get_func_argNames($php_function));
        foreach (get_func_argNames($php_function) as $arg)
        {
            $txt.= "$arg: ${$arg}<br>";
        }
     }
 }

So I wrote a new method to make this easier to maintain:

$_debug_txt = return_debug_header(__FUNCTION__);

function return_debug_header($php_function)
{

    // returns debug string to debug handler
    $arr_args = get_func_argNames($php_function);
    $php_function_args  = implode(', ',$arr_args);
    if (is_array($arr_args)) {
        foreach ($arr_args as $arg)
        {
            // $arg shows the right variable NAME, but ${$arg} is null.
            $txt.= "$arg: ${$arg}<br>";
        }
    } else {
        $txt = 'No arguments passed.';
    }

It might be used like this

function validate_date($date)
{

    if ($condition)
    {
        // generate debug header only if debug is true.
        $_debug_txt = return_debug_header(__FUNCTION__);
        // do something with txt...
    }
}

The problem is that variable variables does not appear to work with data retrieved from get_func_argNames. Variable names exist (I can print them to the screen), but the corresponding value appears blank.

PHP warns that variable variables do not work with superglobals, however it is not clear whether data returned from get_func_argNames is considered "superglobal".

Is anyone seeing anything else that could be causing variable variables not to work inside this function?


Solution

  • You can't access local variables in one function from another function. Variable variables only operate within the local scope. So you need to pass the arguments as an array to the debug function.

    function return_debug_header($php_function, $args)
    {
    
        // returns debug string to debug handler
        $arr_args = get_func_argNames($php_function);
        if (is_array($arr_args)) {
            foreach ($arr_args as $i => $arg)
            {
                $txt.= "$arg: {$args[$i]}<br>";
            }
        } else {
            $txt = 'No arguments passed.';
        }
    }
    

    Use this as:

    $_debug_text = return_debug_header(__FUNCTION__, func_get_args());