Canol Gökel


Sloganı olmayan blog

Variable variable names; PHP and others…

As you might know, in PHP you can easily use a variable to name another variable. For example,

$example = "canol";

Now, we will create a variable named “canol” with value “gokel”:

$$example = "gokel";

This is a really useful feature. But the community of other languages just can’t seem to accept it. Ask them how to use variables variable names and they will answer: “Use hashes, using variable variable names is stupid”. There are even some articles about it being stupid:

Although in the case of given examples in the link I’ve given above it is true, this is not the case always. I’ll give you a simple idea of a program and tell me how to do this using hash tables.

Suppose we have program, which asks user to enter a variable name, and the program looks whether that variable is defined in itself, then prints its value if it is defined. Can you write this program without using variable variable names? Well, if you consider writing an hash table which will include all the variable names you use and updating it whenever you change your program “not being stupid”, then, yes you can…

Filed under: Programming, , , , ,