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

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

    It may be considered quick and dirty, but my own personal preference is to use a function/method like this:

    public function getVarName($var) {      
      $tmp = array($var => '');
      $keys = array_keys($tmp);
      return trim($keys[0]);
    }
    

    basically it just creates an associative array containing one null/empty element, using as a key the variable for which you want the name.

    we then get the value of that key using array_keys and return it.

    obviously this gets messy quick and wouldn't be desirable in a production environment, but it works for the problem presented.

提交回复
热议问题