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

前端 未结 24 1394
南旧
南旧 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条回答
  •  -上瘾入骨i
    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)."
    "; //$B echo getReference($C)."
    "; //$C $D->whatIs(); //$D

提交回复
热议问题