Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's an actual use of variable variables?

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?

like image 993
user151841 Avatar asked Aug 19 '10 15:08

user151841


2 Answers

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.

like image 175
Artefacto Avatar answered Oct 08 '22 23:10

Artefacto


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.

like image 31
Matthew Avatar answered Oct 09 '22 00:10

Matthew