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

前端 未结 24 1387
南旧
南旧 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:09

    Many replies question the usefulness of this. However, getting a reference for a variable can be very useful. Especially in cases with objects and $this. My solution works with objects, and as property defined objects as well:

    function getReference(&$var)
    {
        if(is_object($var))
            $var->___uniqid = uniqid();
        else
            $var = serialize($var);
        $name = getReference_traverse($var,$GLOBALS);
        if(is_object($var))
            unset($var->___uniqid);
        else
            $var = unserialize($var);
        return "\${$name}";    
    }
    
    function getReference_traverse(&$var,$arr)
    {
        if($name = array_search($var,$arr,true))
            return "{$name}";
        foreach($arr as $key=>$value)
            if(is_object($value))
                if($name = getReference_traverse($var,get_object_vars($value)))
                    return "{$key}->{$name}";
    }
    

    Example for the above:

    class A
    {
        public function whatIs()
        {
            echo getReference($this);
        }
    }
    
    $B = 12;
    $C = 12;
    $D = new A;
    
    echo getReference($B)."<br/>"; //$B
    echo getReference($C)."<br/>"; //$C
    $D->whatIs(); //$D
    
    0 讨论(0)
  • 2020-11-22 02:10

    I think you want to know variable name with it's value. You can use an associative array to achieve this.

    use variable names for array keys:

    $vars = array('FooBar' => 'a string');
    

    When you want to get variable names, use array_keys($vars), it will return an array of those variable names that used in your $vars array as it's keys.

    0 讨论(0)
  • 2020-11-22 02:11

    Use this to detach user variables from global to check variable at the moment.

    function get_user_var_defined () 
    {
        return array_slice($GLOBALS,8,count($GLOBALS)-8);     
    }
    
    function get_var_name ($var) 
    {
        $vuser = get_user_var_defined(); 
        foreach($vuser as $key=>$value) 
        {
            if($var===$value) return $key ; 
        }
    }
    
    0 讨论(0)
  • 2020-11-22 02:12

    You might consider changing your approach and using a variable variable name?

    $var_name = "FooBar";
    $$var_name = "a string";
    

    then you could just

    print($var_name);
    

    to get

    FooBar
    

    Here's the link to the PHP manual on Variable variables

    0 讨论(0)
  • 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.");
    }
    
    0 讨论(0)
  • 2020-11-22 02:14

    I couldn't think of a way to do this efficiently either but I came up with this. It works, for the limited uses below.

    shrug

    <?php
    
    function varName( $v ) {
        $trace = debug_backtrace();
        $vLine = file( __FILE__ );
        $fLine = $vLine[ $trace[0]['line'] - 1 ];
        preg_match( "#\\$(\w+)#", $fLine, $match );
        print_r( $match );
    }
    
    $foo = "knight";
    $bar = array( 1, 2, 3 );
    $baz = 12345;
    
    varName( $foo );
    varName( $bar );
    varName( $baz );
    
    ?>
    
    // Returns
    Array
    (
        [0] => $foo
        [1] => foo
    )
    Array
    (
        [0] => $bar
        [1] => bar
    )
    Array
    (
        [0] => $baz
        [1] => baz
    )
    

    It works based on the line that called the function, where it finds the argument you passed in. I suppose it could be expanded to work with multiple arguments but, like others have said, if you could explain the situation better, another solution would probably work better.

    0 讨论(0)
提交回复
热议问题