user198729
user198729

Reputation: 63646

How to get variable name in PHP?

func($name1) should return name1

Is it possible?

Upvotes: 4

Views: 858

Answers (5)

edorian
edorian

Reputation: 38961

Good Idea ? No

Any usecase you where you should do it ? No

Proof of concept ? Sure !

<?php

a($test);


function a($x) {
    $trace = debug_backtrace();
    $file = file($trace[0]['file']);
    $line = $file[$trace[0]['line']-1];

    var_dump($line); // Prints "a($test);" Do the Stringparsing and your done

}

Yes, this takes the "easy" by reading the sourcefile, it is also doable by using a php extension called "bytekit" that gives you userland access to the php opcodes and work from there.

Upvotes: 2

Jivlain
Jivlain

Reputation: 3658

Obviously, it is possible for sufficiently high values of crazy.

The comments on this page include several techniques: http://php.net/manual/en/language.variables.php

lucas dot karisny at linuxmail dot org's answer works on my machine: http://www.php.net/manual/en/language.variables.php#49997

YMMV.

Upvotes: 1

andyjdavis
andyjdavis

Reputation: 349

Here's a function that does it.

function var_name (&$iVar, &$aDefinedVars)
{
    foreach ($aDefinedVars as $k=>$v)
        $aDefinedVars_0[$k] = $v;

    $iVarSave = $iVar;
    $iVar     =!$iVar;

    $aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));
    $iVar      = $iVarSave;

    return $aDiffKeys[0];
}

Call it like this

$test = "blah";
echo var_name($test,  get_defined_vars());

That will print out "test".

I originally found that function over here You can also do it by iterating over the array returned by get_defined_vars(). That might be a bit easier to understand.

Upvotes: 7

Mike Trpcic
Mike Trpcic

Reputation: 25659

No.

When you define a function, you specify a local variable name for it to have inside the scope of that function. PHP will pass the function the appropriate value, but the symbol is no longer in scope.

You could look into using "variable variables" as an alternative, however.

Upvotes: 1

Pascal MARTIN
Pascal MARTIN

Reputation: 401002

No, there is no way to get the name of a variable in PHP.

When calling a function, that function will only receive the content of the variable, and not the "variable itself" -- which means a function cannot find out the name of the variable that was passed to it.

Upvotes: 3

Related Questions