0

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!

joshwoodward
  • 201
  • 2
  • 10
  • possible duplicate of [Determine original name of variable after its passed to a function](http://stackoverflow.com/questions/3404057/determine-original-name-of-variable-after-its-passed-to-a-function) – deceze Jan 30 '14 at 16:23
  • `$arg = func_get_arg(0);var_export($arg);` may do it. Ignore that perhaps not. What about using a class rather than a function and then using reflection perhaps get get the class param list? – Dave Jan 30 '14 at 16:24
  • @deceze realised that myself after I went and read up on those to buit in funcs :) – Dave Jan 30 '14 at 16:27
  • http://www.php.net/manual/en/class.reflectionparameter.php perhaps ? – Dave Jan 30 '14 at 16:29
  • @deceze: That's Javascript, not PHP. – joshwoodward Jan 30 '14 at 16:44
  • Oops, my bad. I've answered this in about every language now... ;) Not exactly but kind of a dupe of http://stackoverflow.com/questions/20613693/php-is-it-possible-to-identify-the-name-of-the-variable-containing-the-object/ then. – deceze Jan 30 '14 at 16:46
  • Or http://stackoverflow.com/questions/255312/how-to-get-a-variable-name-as-a-string-in-php – deceze Jan 30 '14 at 16:51

1 Answers1

1

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
Gus Hogg-Blake
  • 2,393
  • 2
  • 21
  • 31