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

前端 未结 24 1920
南旧
南旧 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 01:56

    Adapted from answers above for many variables, with good performance, just one $GLOBALS scan for many

    function compact_assoc(&$v1='__undefined__', &$v2='__undefined__',&$v3='__undefined__',&$v4='__undefined__',&$v5='__undefined__',&$v6='__undefined__',&$v7='__undefined__',&$v8='__undefined__',&$v9='__undefined__',&$v10='__undefined__',&$v11='__undefined__',&$v12='__undefined__',&$v13='__undefined__',&$v14='__undefined__',&$v15='__undefined__',&$v16='__undefined__',&$v17='__undefined__',&$v18='__undefined__',&$v19='__undefined__'
    ) {
        $defined_vars=get_defined_vars();
    
        $result=Array();
        $reverse_key=Array();
        $original_value=Array();
        foreach( $defined_vars as $source_key => $source_value){
            if($source_value==='__undefined__') break;
            $original_value[$source_key]=$$source_key;
            $new_test_value="PREFIX".rand()."SUFIX";
            $reverse_key[$new_test_value]=$source_key;
            $$source_key=$new_test_value;
    
        }
        foreach($GLOBALS as $key => &$value){
            if( is_string($value) && isset($reverse_key[$value])  ) {
                $result[$key]=&$value;
            }
        }
        foreach( $original_value as $source_key => $original_value){
            $$source_key=$original_value;
        }
        return $result;
    }
    
    
    $a = 'A';
    $b = 'B';
    $c = '999';
    $myArray=Array ('id'=>'id123','name'=>'Foo');
    print_r(compact_assoc($a,$b,$c,$myArray) );
    
    //print
    Array
    (
        [a] => A
        [b] => B
        [c] => 999
        [myArray] => Array
            (
                [id] => id123
                [name] => Foo
            )
    
    )
    

提交回复
热议问题