0

Possible Duplicate:
How to get a variable name as a string in PHP?

Example:

Can something like this be achieved in PHP?

$Age = 43;

output_variable_name_and_value($Age);

    /*
    outputs:
    "The requested variable name is Age and its current value is 43"; 
    */


//If possible, how would the line marked below with ? ? ? ? be?

function output__variable_name_and_value($input)

{

    $var_name = get_name_somehow($input);   // ? ? ? ? 

    echo "The requested variable name is {$var_name} 
          and its current value is {$input}";

}   
Community
  • 1
  • 1
Average Joe
  • 4,521
  • 9
  • 53
  • 81
  • Please make sure you code works – PeeHaa Jun 19 '12 at 12:25
  • 2
    From the accepted answer to the duplicate question: "to be clear, there is no good way to do this in PHP, which is probably because you shouldn't have to do it. There are probably better ways of doing what you're trying to do." – lonesomeday Jun 19 '12 at 12:29

3 Answers3

1

You can use this function:

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:

var_name($Age, get_defined_vars());

Source: http://mach13.com/how-to-get-a-variable-name-as-a-string-in-php

Jeroen
  • 13,056
  • 4
  • 42
  • 63
1

This is not possible, easily. You have to use $GLOBALS;

function get_variable_name($var) {
    foreach($GLOBALS as $k => $v) {
        if ($v === $var) {
            return $k;
        }
    }
    return false;
}

The only downfall is, it may return a different variable name if they both have the same value.

Or this,

function varName( $v ) {
    $trace = debug_backtrace();
    $vLine = file( __FILE__ );
    $fLine = $vLine[ $trace[0]['line'] - 1 ];
    preg_match( "#\\$(\w+)#", $fLine, $match );
    print_r( $match );
}

which I found here: How to get a variable name as a string in PHP?

Community
  • 1
  • 1
472084
  • 17,666
  • 10
  • 63
  • 81
1

Well..

You can figure out what called the output__variable_name_and_value function using debug_backtrace.

Then you know a filename and line number, so you could try to parse the sourcefile and figure out whats between output__variable_name_and_value( and ).

Probably a bad idea though!

Evert
  • 93,428
  • 18
  • 118
  • 189