2 ms·
Oof, I'm not a PHP coder and I didn't know it had this feature before reading these comments but I definitely do not envy it in the languages I use. The potenti
by simias 6y ago
Oof, I'm not a PHP coder and I didn't know it had this feature before reading
these comments but I definitely do not envy it in the languages I use. The
potential for abuse is immense, this is one step removed from generating code at
runtime by concatenating strings and calling eval() on them.
I'm sure there are situations where this feature can be really valuable (and I
do sometimes use getattr/setattr in python, which is somewhat similar) but I
think the developers should really think hard and make an educated decision
about when to use it. As such having it require a bit of boilerplate is a
feature more than a bug IMO. I definitely wouldn't want to have to maintain code
written by someone who abuses these types of indirections everywhere.
I can definitely imagine a novice coder using these "variable variables" in lieu
of a proper hash table or dictionary object for instance.
I mean it suffices to read some of the comments to the article posted above to
find a bunch of people posting code snippets which, IMO, are a very poor way of
implementing what they want. For instance:
$price_for_monday = 10;
$price_for_tuesday = 20;
$price_for_wednesday = 30;
$today = 'tuesday';
$price_for_today = ${ 'price_for_' . $today};
echo $price_for_today; // will return 20
or even:
class foo {
function bar() {
$bar1 = "var1";
$bar2 = "var2";
$this->{$bar1}= "this ";
$this->{$bar2} = "works";
}
}
$test = new foo;
$test->bar();
echo $test->var1 . $test->var2;
I'd probably quit if I had to maintain code written like that. Having
boilerplate would at least make it obvious that something unusual is going on
with these variables and make the intent clear while reading the code.
- fendy3002 6y agoThats because your use case isn't real. In js, its usually used to generate select option (example in react): for(let optValue of Object.keys(options)){ optDom.push( <option key={optValue} value={optValue}>{options[optValue]}</option> ) } Of course array also works, but with json object, it guarantee that the value will be distinct and you don't need specific array object type.