0

I want the variable name from example: ${'tell'.$var.'How}. I've tried a couple of the examples varName(); from How to get a variable name as a string in PHP?, but I didn't get it working. Any idea how to get this working?

<?php
    $var = 'Me';
    ${'tell'.$var.'How'} = 'Thanks!';
    $name = varName(${'tell'.$var.'How'});

    // Varialbe name: $tellMeHow = Thanks! 
    echo 'Variable name: $'.$name.' = '.${'tell'.$var.'How'}; 
?>

Function:

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

Is it possible that a variable is its own name?

<?php
    $var = 'is my name '.varName().'?';
    echo $var; // is my name var?

    $why = 'Why '.$var;
    echo $why; // Why is my name var?
?>

Cool if someone knows this... and what's to tell me. ;)

Wobbo
  • 140
  • 1
  • 9
  • Can you explain more clearly? What is the result now and what is your expected result – Ngo Tuan Jan 07 '18 at 07:21
  • You passing $v into `varName()` which doesn't do anything. But in your last example you don't pass anything, which causes an error. – Nigel Ren Jan 07 '18 at 08:10

1 Answers1

-1

These are known as "variable variables" and are described in the PHP documentation.

kmoser
  • 8,780
  • 3
  • 24
  • 40