Variable variables seem pretty cool, but I can't think of a scenario where one would actually use them in a production environment. What would such a scenario be? How were they used?
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.
A variable variable is essentially an array (map/dictionary). The following are equivalent ideas:
<?php
$foo = array('a' => 1);
$bar = 'a';
echo $foo[$bar]."\n";
$foo_a = 1;
$bar = 'a';
$vv = "foo_$bar";
echo $$vv."\n";
?>
Thus if you wrap your "variable variables" into a parent array, you can do away with them.
I've seen people use variable properties inside classes:
<?php
class Foo
{
private $a = 1;
public function __get($key)
{
if (isset($this->$key)) return $this->$key;
}
}
$foo = new Foo();
echo $foo->a;
?>
But again, you could use an array:
<?php
class Foo
{
private $props = array('a' => 1);
public function __get($key)
{
if (array_key_exists($key, $this->props))
return $this->props[$key];
}
}
$foo = new Foo();
echo $foo->a;
?>
And outside classes:
<?php
class Foo
{
public $a = 1;
}
$foo = new Foo();
$prop = 'a';
echo $foo->{$prop};
?>
So you never "have" to use variable variables or variable properties when writing your own controlled code. My personal preference is to never use variable variables. I occasionally use variable properties, but prefer to use arrays when I'll be accessing data in that way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With