January 30th, 2007

Using variable variables

Posted by Jeremy2 in PHP

This is just a really quick one, as it is fairly simple, but I have never seen anybody else do this for objects / functions in PHP so I wanted to write this down before I forgot it. It took me a while to figure out how to do variable variables for objects, but I never realized that you can also call functions and create new objects using variables. For those of you who do not know what a variable variable is, here is a quick demonstration:


< ?php
$test = "Hello!";
$some_var = 'test';
echo ${$test};
?>

The brackets around the variable name are optional. What this does, is it takes any string (whether in variable form or a plain string) and it treats it just like it’s a variable. You can also do string concatenation in the variable name like so:

$some_test = 'Hello!';
$some_var = 'test';
echo ${'some_'.$some_var};

In this case, the brackets are not optional. What I did not realize is that you can also have variable functions and variable classes, like so:


class some_class {/*empty class*/}
class some_other_class {/*empty class*/}
function some_func($a) {
echo $a;
}
$the_class_name = 'some_class';
//Creates a new instance of some_class
$new_obj = new $the_class_name;
$the_func_name = 'some_func';
$the_func_name('Hello!');

To use variable variables in objects, this is how you do it:


$obj = (object) NULL;
$obj->some_var = 'Hello!';
$var_name = 'some_var';
echo ($obj->$var_name);

To access functions using a variable, here is code:


function print_test($a) {
print $a;
}

$func_name = 'print_test';
$func_name('Hello!');

You can use a similar syntax to access functions in objects as you can to access the variables: just put the variable that contains the string with the parentheses around the arguments like this:


$obj->$func_name('Some argument');

(more…)