假设我有这样的PHP代码:

$FooBar = "a string";

然后我需要一个这样的函数:

print_var_name($FooBar);

打印:

FooBar

有什么想法如何实现这一点?这在PHP中可能吗?


当前回答

我实际上有一个有效的用例。

我有一个函数cacheVariable($var)(好吧,我有一个函数缓存($key, $value),但我想有一个函数如上所述)。

目的是:

$colour = 'blue';
cacheVariable($colour);

...

// another session

...

$myColour = getCachedVariable('colour');

我试过了

function cacheVariable($variable) {
   $key = ${$variable}; // This doesn't help! It only gives 'variable'.
   // do some caching using suitable backend such as apc, memcache or ramdisk
}

我也试过

function varName(&$var) {
   $definedVariables = get_defined_vars();
   $copyOfDefinedVariables = array();
   foreach ($definedVariables as $variable=>$value) {
      $copyOfDefinedVariables[$variable] = $value;
   }
   $oldVar = $var;
   $var = !$var;
   $difference = array_diff_assoc($definedVariables, $copyOfDefinedVariables);
   $var = $oldVar;
   return key(array_slice($difference, 0, 1, true));
}

但这也失败了……:(

当然,我可以继续做缓存(' color ', $ color),但我很懒,你知道…;)

所以,我想要的是一个函数,它得到一个变量的原始名称,因为它被传递给一个函数。在函数内部,我不可能知道这一点。在上面的第二个例子中,通过引用传递get_defined_vars()在一定程度上帮助了我(感谢Jean-Jacques Guegan的这个想法)。后一个函数开始工作,但它仍然只返回局部变量('variable',而不是' color ')。

我还没有尝试使用get_func_args()和get_func_arg(), ${}-构造和key()组合,但我认为它也会失败。

其他回答

为什么不构建一个简单的函数,然后告诉它呢?

/**
 * Prints out $obj for debug
 *
 * @param any_type $obj
 * @param (string) $title
 */
function print_all( $obj, $title = false )
{
    print "\n<div style=\"font-family:Arial;\">\n";
    if( $title ) print "<div style=\"background-color:red; color:white; font-size:16px; font-weight:bold; margin:0; padding:10px; text-align:center;\">$title</div>\n";
    print "<pre style=\"background-color:yellow; border:2px solid red; color:black; margin:0; padding:10px;\">\n\n";
    var_export( $obj );
    print "\n\n</pre>\n</div>\n";
}

print_all( $aUser, '$aUser' );

如果变量是可交换的,那么必须在某个地方有逻辑来决定使用哪个变量。你所需要做的就是在你做其他事情的时候,把变量名放在这个逻辑中的$variable中。

我想我们都很难理解你需要这个做什么。示例代码或对实际要做的事情的解释可能会有所帮助,但我怀疑您想得太多了。

我知道这个问题很老了,而且已经有人回答了,但我其实是在找这个。我把这个答案贴出来是为了给大家节省一点时间来完善一些答案。

选项1:

$data = array('$FooBar');  

$vars = [];  
$vars = preg_replace('/^\\$/', '', $data); 

$varname = key(compact($vars));  
echo $varname;

打印:

FooBar

不管出于什么原因,你会发现自己处于这样的情况下,它确实有效。

. 选项2:

$FooBar = "a string";  

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

如果$FooBar拥有一个唯一的值,它将打印'FooBar'。如果$FooBar为空或空,它将打印找到的第一个空字符串或空字符串的名称。

它可以这样使用:

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

您可以使用get_defined_vars()来查找与您试图查找的变量名称具有相同值的变量的名称。显然这并不总是有效,因为不同的变量通常有相同的值,但这是我能想到的唯一方法。

编辑:get_defined_vars()似乎没有正确工作,它返回'var',因为$var在函数本身中使用。$GLOBALS似乎可以,所以我把它改成了这个。

function print_var_name($var) {
    foreach($GLOBALS as $var_name => $value) {
        if ($value === $var) {
            return $var_name;
        }
    }

    return false;
}

编辑:需要明确的是,在PHP中没有好的方法来做到这一点,这可能是因为您不应该这样做。也许有更好的方法来做你想做的事情。

出于调试的原因,我做了一个检查函数。它就像print_r()的类固醇,很像Krumo,但对对象更有效一点。我想添加var名称检测,灵感来自于Nick Presta的帖子。它检测作为参数传递的任何表达式,而不仅仅是变量名。

这只是检测传递表达式的包装器函数。 大多数案子都没问题。 如果在同一行代码中多次调用该函数,则它将不起作用。

这很好: 死(检查($ this - > getUser()——> hasCredential(“删除”)));

Inspect()是检测传递表达式的函数。

我们得到:$this->getUser()->hasCredential("delete")

function inspect($label, $value = "__undefin_e_d__")
{
    if($value == "__undefin_e_d__") {

        /* The first argument is not the label but the 
           variable to inspect itself, so we need a label.
           Let's try to find out it's name by peeking at 
           the source code. 
        */

        /* The reason for using an exotic string like 
           "__undefin_e_d__" instead of NULL here is that 
           inspected variables can also be NULL and I want 
           to inspect them anyway.
        */

        $value = $label;

        $bt = debug_backtrace();
        $src = file($bt[0]["file"]);
        $line = $src[ $bt[0]['line'] - 1 ];

        // let's match the function call and the last closing bracket
        preg_match( "#inspect\((.+)\)#", $line, $match );

        /* let's count brackets to see how many of them actually belongs 
           to the var name
           Eg:   die(inspect($this->getUser()->hasCredential("delete")));
                  We want:   $this->getUser()->hasCredential("delete")
        */
        $max = strlen($match[1]);
        $varname = "";
        $c = 0;
        for($i = 0; $i < $max; $i++){
            if(     $match[1]{$i} == "(" ) $c++;
            elseif( $match[1]{$i} == ")" ) $c--;
            if($c < 0) break;
            $varname .=  $match[1]{$i};
        }
        $label = $varname;
    }

    // $label now holds the name of the passed variable ($ included)
    // Eg:   inspect($hello) 
    //             => $label = "$hello"
    // or the whole expression evaluated
    // Eg:   inspect($this->getUser()->hasCredential("delete"))
    //             => $label = "$this->getUser()->hasCredential(\"delete\")"

    // now the actual function call to the inspector method, 
    // passing the var name as the label:

      // return dInspect::dump($label, $val);
         // UPDATE: I commented this line because people got confused about 
         // the dInspect class, wich has nothing to do with the issue here.

    echo("The label is: ".$label);
    echo("The value is: ".$value);

}

下面是inspector函数(和我的dInspect类)的一个例子:

http://inspect.ip1.cc

该页面的文本是西班牙语,但代码简洁,非常容易理解。