【问题标题】:Can a PHP variable know its name? [duplicate]PHP 变量可以知道它的名字吗? [复制]
【发布时间】:2012-06-19 20:26:20
【问题描述】:

可能重复:
How to get a variable name as a string in PHP?

例子:

这样的事情可以在 PHP 中实现吗?

$Age = 43;

output_variable_name_and_value($Age);

    /*
    outputs:
    "The requested variable name is Age and its current value is 43"; 
    */


//If possible, how would the line marked below with ? ? ? ? be?

function output__variable_name_and_value($input)

{

    $var_name = get_name_somehow($input);   // ? ? ? ? 

    echo "The requested variable name is {$var_name} 
          and its current value is {$input}";

}   

【问题讨论】:

  • 请确保您的代码有效
  • 从接受的答案到重复问题:“要清楚,在 PHP 中没有好的方法可以做到这一点,这可能是因为你不应该这样做。可能有更好的做你想做的事的方法。”

标签: php variables


【解决方案1】:

这是不可能的,很容易。你必须使用 $GLOBALS;

function get_variable_name($var) {
    foreach($GLOBALS as $k => $v) {
        if ($v === $var) {
            return $k;
        }
    }
    return false;
}

唯一的缺点是,如果它们的值相同,它可能会返回不同的变量名。

或者这个,

function varName( $v ) {
    $trace = debug_backtrace();
    $vLine = file( __FILE__ );
    $fLine = $vLine[ $trace[0]['line'] - 1 ];
    preg_match( "#\\$(\w+)#", $fLine, $match );
    print_r( $match );
}

我在这里找到的:How to get a variable name as a string in PHP?

【讨论】:

    【解决方案2】:

    你可以使用这个功能:

    function var_name(&$iVar, &$aDefinedVars) {
        foreach ($aDefinedVars as $k=>$v)
            $aDefinedVars_0[$k] = $v;
    
        $iVarSave = $iVar;
        $iVar     =!$iVar;
    
        $aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));
        $iVar      = $iVarSave;
    
        return $aDiffKeys[0];
    }
    

    这样称呼它:

    var_name($Age, get_defined_vars());
    

    来源:http://mach13.com/how-to-get-a-variable-name-as-a-string-in-php

    【讨论】:

      【解决方案3】:

      嗯..

      您可以使用 debug_backtrace 找出所谓的 output__variable_name_and_value 函数。

      然后您知道文件名和行号,因此您可以尝试解析源文件并找出output__variable_name_and_value() 之间的内容。

      虽然可能是个坏主意!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-03
        • 2011-10-08
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 2022-11-01
        • 1970-01-01
        相关资源
        最近更新 更多