What's an Actual Use of Variable Variables

What's an actual use of variable variables?

Its purpose, I guess, is to allow novice programmers to dynamically change data without using "complicated stuff" like composite types (arrays and objects).

I never use them.

Variable variables in PHP - What is their purpose?

Sometimes we need software that is extremely flexible and that we can parametrize. You have to prepare the whole thing, of course, but part of it just comes from user input, and we have no time to change the software just because the user needs a new input.

With variable variables and variable functions you can solve problems that would be much harder to solve without them.

Quick Example:


Without variable variables:


$comment = new stdClass(); // Create an object

$comment->name = sanitize_value($array['name']);
$comment->email = sanitize_values($array['email']);
$comment->url = sanitize_values($array['url']);
$comment->comment_text = sanitize_values($array['comment_text']);

With variable variables


$comment = new stdClass(); // Create a new object

foreach( $array as $key=>$val )
{
$comment->$key = sanitize_values($val);
}

Why use dynamic variables (variable variables) in PHP or other languages

I had voted to close this question (vote since retracted) on the basis of it being subjective, but on reflection, I think I can give an objective answer.

A static variable name is a sequence of characters, representing a token which the underlying engine uses as a label to identify the value the variable represents (very very layperson's description).

A "sequence of characters" is a string. A string is an expression that represents a string. So from there it stands to reason that any expression that represents a string ought to be good enough to represent the token that refers to a variable. And that expression itself could be assigned to a variable, and from there one gets dynamic variable names.

But this is not what you asked. You asked: why?

It's not for the implementors of the language to answer questions like that. It's their job to provide a uniform and predictable programming interface, via their language. It's uniform to be able to represent a sequence of characters via an expression which in turn could be represented by a variable. Job done.

Subjectively, I could potentially see where some data is imported from an external source, and even the schema of the data is dynamic. One might want to represent that in some sort of generic object fashion, and it leads from there that the names of the properties of the object might also be dynamic. Whether or not this might be a good approach to the problem at hand is entirely subjective, and down to the developer's judgement, and that of their peers during code review.

Another example might be that you've inherited some shoddy spaghetti code where "needs must" and using dynamic naming - for whatever reason - might be a good approach.

PHP's burden ends at providing the mechanism to write the code; it does not speak to the quality of the design of said code. That's what code review is for.

what are the major advantages of using variable variables in php?

you can use it in case of not-user-input. Look

function getVar($gid){
$name = "gid".$gid;
global $$name;
$var = $$name;
return $var;
}

It's useful when you have a lot of variables (same start with ending number, etc...) which is probably save

Variable variables: when useful?

Never. This feature should be banned from the language as well as its other children diseases such as register globals, magic quotes, etc.

When to use PHP's variable variables?

You use variable interpretation in situations when you need to dynamically reference a variable and don't want to use an array. Generally I would not recommend using it, as you lose benefits such as static code analysis.

When to use a variable variable in PHP?

One situation where I've had to use them is URI processing, although this technique might be dated, and I admittedly haven't used it in a long time.

Let's say we want to pull the URI from the script in the format domain.tld/controller/action/parameter/s. We could remove the script name using the following:

$uri_string = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['REQUEST_URI']);

To extract the controller, action, and parameter values from this we're going to have to explode the string using the path delimiter '/'. However, if we have leading or trailing delimiters, we'll have empty array values upon explosion, so we should trim those from the beginning and end of the string:

$uri_string = trim($uri_string, '/');

We can now explode the path into an array:

$uri_data = explode('/', $uri_string);

$uri_data[0] now contains our controller name, $uri_data[1] contains the action name, and values in the array beyond that are parameters that should be passed to the action method.

$controller_name = $uri_data[0];
$action_name = $uri_data[1];

So, now that we have these names, we can use them for a number of things. If you keep your controllers in a very specific directory relative to the site root, you can use this information to require_once the controller class. At that point, you can instantiate it and call it using variable variables:

$controller = new $controller_name();
$controller->{$action_name}(); // Or pass parameters if they exist

There are a lot of security gotchas to look out for in this approach, but this is one way I've seen to make use of variable variables.

DISCLAIMER: I'm not suggesting your actually use this code.

What are the real-world uses of Constants in Programming?

By defining a constant, you won't need to put the same values hardcoded in your code periodically. You can avoid repetition. And you can modify these group values at once by modifying their definition.

C variable variables

Your question is still a little unclear (as indicated by the assortment of interpretations in the answers). I'm assuming that you want to refer to pins by physical pin number. If this is not correct, please clarify your question so we can provide better answers.

Here's roughly how I would do it if someone held a gun to my head:

DISCLAIMER: I have not tested this nor been particularly careful about checking documentation. The code is written for avr-gcc/avr-libc on Linux, though it may work elsewhere.

// Map from physical pin number to associated direction register.
volatile uint8_t *ddr_map[] = {
NULL, // Vcc, GND, or some other non-IO pin.
&DDRB,
&DDRB,
&DDRC,
// etc... Values will vary for different target chips.
};

// Map from physical pin number to port mask.
uint8_t mask_map[] = {
0x00,
_BV(0),
_BV(1),
_BV(0),
// etc... Values will vary for different target chips.
}

typedef enum {
IN,
OUT
} PinDir;

void setMode(int pin, PinDir dir) {
if(dir == OUT) {
*ddr_map[pin] |= mask_map[pin];
} else {
*ddr_map[pin] &= ~mask_map[pin];
}
}

See http://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_port_pass

And here's why it's not a good idea:


  1. It doesn't abstract away any meaningful behavior (it actually removes abstraction -- the physical pin number is lower level than the logical port/pin). Moreover, the physical pin number is not necessarily the same for different package formats. The pins of PORTB may not be assigned to the same physical pin numbers on a QFP package as a PDIP package. So this code is actually more confusing.

  2. It adds overhead. You have an extra function call (which costs cycles and stack) and two (or more) arrays used for lookups (which cost flash and RAM on the AVR unless you take special measures, in which case they cost extra cycles and flash or EEPROM) not to mention all the indirections (array lookups, pointer dereferencing) and the extra compare and branch. In desktop & web development you would be right to laugh at my concern over such small costs, but on AVR that waste has considerably more impact. (NOTE: You might be able to convince the compiler to optimize some of this out, but if you are using -Os it will be difficult. And now you're worrying about even lower level details than before...)

  3. The provided means of manipulating pins is not so complicated as to be worth hiding in this way. You should get comfortable with converting between hexadecimal and binary in your head (it's not hard). Even if you don't want to mess with hex, the _BV() macro makes pin manipulations pretty easy (or just use (1 << x) which is more portable and will be recognized by more programmers).

By the way, PORTB, DDRB, etc. are not constants. They are variables that are tied to specific addresses or registers. Trying to modify a constant with something like CONST_THINGY |= 0x03 would produce a compiler error.

Variable variables

C does not have the feature you described. It is a low level language (it is sometimes described as "high-level assembly") that doesn't provide many fancy features (by today's standards). This is why it is the language of choice for AVR -- you want to be close to the hardware, and you don't want lots of extra overhead.

What C does have is pointers. Based on your question and comments I would guess that you aren't very familiar with them, so here's a quick explanation:

  • The & operator returns a pointer to a variable, and is used like this: pointer = &variable;
  • * actually has a couple of uses.

    • The first is declaring a pointer variable (i.e. a variable that holds a pointer instead of an int, char, or float): int *pointer; Notice that you have to specify what type of variable it will point at.
    • The second use is what is called dereferencing a pointer. Basically, this means accessing a variable through the pointer. If pointer points at variable, *pointer = 42; will set variable equal to 42, and other_var = *pointer will set other_var to the value of variable.
  • There is also pointer arithmetic, but that's beyond the scope of this answer.

The point of all this is that you can effectively treat variables themselves like values, storing them and passing them around. You can't really modify them in any meaningful way other than manipulating their value, but you don't need to either.



Related Topics



Leave a reply



Submit