Bryan Zwicker
Bryan Zwicker

Reputation: 652

Get passed variable name as string

I am trying to create a function that adds data to a PHP session array. I want to dynamically create the Key of the array item as the variable name, and set the value of said key to that variables value. My example code so far:

$foo = 'bar';
addHookpointVar($foo);

function addHookpointVar($var) {
    $_SESSION['HOOKPOINT']['foo'] = $var;
}

Is there a method in PHP to get a string representation of a variable, such that my $_SESSION['HOOKPOINT']['VAR'] will be set to the name of the variable passed in?

All the methods I have found involve looping through every variable in the $_GLOBALS

Upvotes: 1

Views: 757

Answers (2)

Nico2am
Nico2am

Reputation: 1

I was also looking for a solution to convert a variable name as string. Having not found the correct answer, I created a function for this problem.

<?php
function func(&$variable) {
    $backupValue = $variable;
    $variable = uniqid();
    foreach ($GLOBALS as $key => $value) {
        if (!is_array($key) && $value == $variable) {
            $variable = $backupValue;
            return $key;
        }
    }
    throw new Exception('error number xx');
}

$test1 = "This is a test";
$test2 = 'This is a second test';
$test3 = 'This is a second test';

$array = [];

$array[func($test1)] = $test1;
$array[func($test2)] = $test2;
$array[func($test3)] = $test3;

var_dump($array);
?>

(Also available on Github.)

Upvotes: -1

AbraCadaver
AbraCadaver

Reputation: 78994

Here's one way:

$foo = 'bar';
addHookpointVar(compact('foo'));

function addHookpointVar($var) {
    list($key, $val) = each($var);
    $_SESSION['HOOKPOINT'][$key] = $val;
}

Or maybe cleaner for the function:

function addHookpointVar($var) {
    $_SESSION['HOOKPOINT'] = array_merge($_SESSION['HOOKPOINT'], $var);
}

However, I would probably just use an array $hp['foo'] = 'bar'; and then you can pass $hp into the function.

Upvotes: 4

Related Questions