Is there a way to get the name of a variable? PHP - Reflection

前端 未结 11 587
旧巷少年郎
旧巷少年郎 2020-12-15 08:50

I know this is not exactly reflection, but kind of. I want to make a debug function that gets a variable and prints a var_dump and the variable name.

Of course, when

11条回答
  •  时光说笑
    2020-12-15 09:26

    You can do it by converting the variable to a key/value set before passing it to the function.

    function varName($theVar) {  
       $variableName = key($theVar);  
       $variableValue = $theVar[$variableName];  
       echo ('The name of the variable used in the function call was '.$variableName.'
    '); echo ('The value of the variable used in the function call was '.$variableValue.'
    '); } $myVar = 'abc'; varName(compact('myVar'));

    Though I don't recommend creating a reference to a nameless variable, function varName(&$theVar) works too.

    Since compact() takes the variable name as a string rather than the actual variable, iterating over a list of variable names should be easy.

    As to why you would want to do this -- don't ask me but it seems like a lot of people ask the question so here's my solution.

提交回复
热议问题