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

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

    Lucas on PHP.net provided a reliable way to check if a variable exists. In his example, he iterates through a copy of the global variable array (or a scoped array) of variables, changes the value to a randomly generated value, and checks for the generated value in the copied array.

    function variable_name( &$var, $scope=false, $prefix='UNIQUE', $suffix='VARIABLE' ){
        if($scope) {
            $vals = $scope;
        } else {
            $vals = $GLOBALS;
        }
        $old = $var;
        $var = $new = $prefix.rand().$suffix;
        $vname = FALSE;
        foreach($vals as $key => $val) {
            if($val === $new) $vname = $key;
        }
        $var = $old;
        return $vname;
    }
    

    Then try:

    $a = 'asdf';
    $b = 'asdf';
    $c = FALSE;
    $d = FALSE;
    
    echo variable_name($a); // a
    echo variable_name($b); // b
    echo variable_name($c); // c
    echo variable_name($d); // d
    

    Be sure to check his post on PHP.net: http://php.net/manual/en/language.variables.php

    0 讨论(0)
  • 2020-11-22 01:57

    From php.net

    @Alexandre - short solution

    <?php
    function vname(&$var, $scope=0)
    {
        $old = $var;
        if (($key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && $var = $old) return $key;  
    }
    ?>
    

    @Lucas - usage

    <?php
    //1.  Use of a variable contained in the global scope (default):
      $my_global_variable = "My global string.";
      echo vname($my_global_variable); // Outputs:  my_global_variable
    
    //2.  Use of a local variable:
      function my_local_func()
      {
        $my_local_variable = "My local string.";
        return vname($my_local_variable, get_defined_vars());
      }
      echo my_local_func(); // Outputs: my_local_variable
    
    //3.  Use of an object property:
      class myclass
      {
        public function __constructor()
        {
          $this->my_object_property = "My object property  string.";
        }
      }
      $obj = new myclass;
      echo vname($obj->my_object_property, $obj); // Outputs: my_object_property
    ?>
    
    0 讨论(0)
  • 2020-11-22 01:57

    If the variable is interchangable, you must have logic somewhere that's determining which variable gets used. All you need to do is put the variable name in $variable within that logic while you're doing everything else.

    I think we're all having a hard time understanding what you're needing this for. Sample code or an explanation of what you're actually trying to do might help, but I suspect you're way, way overthinking this.

    0 讨论(0)
  • 2020-11-22 01:59

    I really fail to see the use case... If you will type print_var_name($foobar) what's so hard (and different) about typing print("foobar") instead?

    Because even if you were to use this in a function, you'd get the local name of the variable...

    In any case, here's the reflection manual in case there's something you need in there.

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

    This is exactly what you want - its a ready to use "copy and drop in" function that echo the name of a given var:

    function print_var_name(){
        // read backtrace
        $bt   = debug_backtrace();
        // read file
        $file = file($bt[0]['file']);
        // select exact print_var_name($varname) line
        $src  = $file[$bt[0]['line']-1];
        // search pattern
        $pat = '#(.*)'.__FUNCTION__.' *?\( *?(.*) *?\)(.*)#i';
        // extract $varname from match no 2
        $var  = preg_replace($pat, '$2', $src);
        // print to browser
        echo trim($var);
    }
    

    USAGE: print_var_name($FooBar)

    PRINT: FooBar

    HINT Now you can rename the function and it will still work and also use the function several times in one line! Thanks to @Cliffordlife

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

    I was looking for this but just decided to pass the name in, I usually have the name in the clipboard anyway.

    function VarTest($my_var,$my_var_name){
        echo '$'.$my_var_name.': '.$my_var.'<br />';
    }
    
    $fruit='apple';
    VarTest($fruit,'fruit');
    
    0 讨论(0)
提交回复
热议问题