0

Let's say I have a function that is passed a string:

function foo($var) {
    echo 'Variable Passed: ' . ???
}

I want to print/access the ??? part, so when using the function, I could print the actual string name passed:

foo($myStringName);

Variable Passed: $myStringName

Does PHP have a way of doing the ??? part?

Maurice
  • 468
  • 6
  • 13
  • 1
    What do you mean by `???` – Clement Sam Jul 19 '20 at 01:52
  • Do you want to print the variable name? – Clement Sam Jul 19 '20 at 01:55
  • Yes exactly, i want to print the name of the variable that was passed to the function, while the function is executing. So if I do foo($stringName) it would execute as Variable Passed: $stringName – Maurice Jul 19 '20 at 01:58
  • The name can’t be changed, so it’s ‘$var’. AFAIK there is no “nameof” operator in PHP. See https://stackoverflow.com/q/255312/2864740 (all the presented methods are various hacks that should probably be limited to specific debugging contexts) – user2864740 Jul 19 '20 at 02:00
  • Thanks, I thought as much but figured thought there might be a clever way to do this. – Maurice Jul 19 '20 at 02:01

1 Answers1

0

You can loop through the $GLOBALS variable and check for matching variable name as the one passed

function printVarName($var) {
    foreach($GLOBALS as $varName => $val) {
        if ($val === $var) {
            echo 'Variable Passed: $'.$varName;
        }
    }

    return false;
}

$vars = 1;
printVarName($vars); //prints Variable Passed: $vars
Clement Sam
  • 720
  • 7
  • 17
  • Interesting and cool, but sadly sadly not what I'm after. I don't think what I want to do is possible, but I've found a different way of solving my problem, thanks anyway. – Maurice Jul 20 '20 at 07:02