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!

7
  • possible duplicate of Determine original name of variable after its passed to a function Commented Jan 30, 2014 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? Commented Jan 30, 2014 at 16:24
  • @deceze realised that myself after I went and read up on those to buit in funcs :) Commented Jan 30, 2014 at 16:27
  • php.net/manual/en/class.reflectionparameter.php perhaps ? Commented Jan 30, 2014 at 16:29
  • @deceze: That's Javascript, not PHP. Commented Jan 30, 2014 at 16:44

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, brilliantly twisted, and it works. Many thanks, Gus!

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.