How to get a variable name as a string in PHP?

前端 未结 24 1424
南旧
南旧 2020-11-22 01:35

Say i have this PHP code:

$FooBar = \"a string\";

i then need a function like this:

print_var_name($FooBar);
24条回答
  •  逝去的感伤
    2020-11-22 02:12

    I know this is old and already answered but I was actually looking for this. I am posting this answer to save people a little time refining some of the answers.

    Option 1:

    $data = array('$FooBar');  
    
    $vars = [];  
    $vars = preg_replace('/^\\$/', '', $data); 
    
    $varname = key(compact($vars));  
    echo $varname;
    

    Prints:

    FooBar

    For whatever reason you would find yourself in a situation like this, it does actually work.

    .
    Option 2:

    $FooBar = "a string";  
    
    $varname = trim(array_search($FooBar, $GLOBALS), " \t.");  
    echo $varname;
    

    If $FooBar holds a unique value, it will print 'FooBar'. If $FooBar is empty or null it will print the name of the first empty or null string it finds.

    It could be used as such:

    if (isset($FooBar) && !is_null($FooBar) && !empty($FooBar)) {
        $FooBar = "a string";
        $varname = trim(array_search($FooBar, $GLOBALS), " \t.");
    }
    

提交回复
热议问题