How to get variable name in PHP?

func($name1) should return name1

Is it possible?

+4
source share
6 answers

Here is the function that does this.

 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]; } 

Call it like this:

 $test = "blah"; echo var_name($test, get_defined_vars()); 

This will print a "test."

I initially discovered that there is a function . You can also do this by iterating over the array returned by get_defined_vars (). This may be a little easier to understand.

+7
source

No, there is no way to get the variable name in PHP.

When a function is called, this function receives only the contents of the variable, and not "the variable itself" - this means that the function cannot recognize the name of the variable that was passed to it.

+3
source

Not.

+2
source

A good idea? Not

Do you want you to do this? Not

Proof of concept? Of course!

 <?php a($test); function a($x) { $trace = debug_backtrace(); $file = file($trace[0]['file']); $line = $file[$trace[0]['line']-1]; var_dump($line); // Prints "a($test);" Do the Stringparsing and your done } 

Yes, it takes a β€œsimple” reading of the source file, it can also be done using a php extension called β€œbytekit” that gives you user access to php opcodes and works from there.

+2
source

Not.

When you define a function, you specify the local name of the variable so that it is inside the scope of that function. PHP will pass the corresponding value to the function, but the character is no longer in scope.

Alternatively, you could use " variable variables ".

+1
source

Obviously, with sufficiently large values ​​of madness is possible.

The comments on this page include several methods: http://php.net/manual/en/language.variables.php

lucas dot karisny in linuxmail dot org answers my machine: http://www.php.net/manual/en/language.variables.php#49997

YMMV.

+1
source

Source: https://habr.com/ru/post/1303200/


All Articles