Question

I have a strange question that's probably not possible, but it's worth asking in case there are any PHP internals nerds who know a way to do it. Is there any way to get the variable name from a function call within PHP? It'd be easier to give an example:

function fn($argument) {
    echo SOME_MAGIC_FUNCTION();
}

$var1 = "foo";
$var2 = "bar";

fn($var1); // outputs "$var1", not "foo"
fn($var2); // outputs "$var2", not "bar"

Before you say it - yes, I know this would be a terrible idea with no use in production code. However, I'm migrating some old code to new code, and this would allow me to very easily auto-generate the replacement code. Thanks!

Was it helpful?

Solution

debug_backtrace() returns information about the current call stack, including the file and line number of the call to the current function. You could read the current script and parse the line containing the call to find out the variable names of the arguments.

A test script with debug_backtrace:

<?php
function getFirstArgName() {
    $calls=debug_backtrace();
    $nearest_call=$calls[1];

    $lines=explode("\n", file_get_contents($nearest_call["file"]));

    $calling_code=$lines[$nearest_call["line"]-1];

    $regex="/".$nearest_call["function"]."\\(([^\\)]+)\\)/";

    preg_match_all($regex, $calling_code, $matches);

    $args=preg_split("/\\s*,\\s*/", $matches[1][0]);

    return $args[0];
}

function fn($argument) {
    echo getFirstArgName();
}

$var1 = "foo";
$var2 = "bar";

fn($var1);
fn($var2);
?>

Output:

$var1$var2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top