variable variables

I just see it as being redundant… I don’t understand why example

<?php
$x= “y”;
$y=“z”;
// echo $$x;
// vs
// echo $y
?>

I have never seen it used professionally, and I would likely loose my shit over seeing it in production code.

2 Likes

Variable variables are poorly named (should have been called a pointer), cause code to be hard to read, search for usage, and troubleshoot (variables are ‘magically’ generated and populated/referenced), and are three times slower than using an array for the same data. In every case where you might want to use them, use an array instead. You will end up with clearer and faster code.

2 Likes

Like phdr said, use arrays insead.

# http://localhost/variable-variable-test.php?color=red

$color = $_GET['color'];

$red = '#ff0000';
$green = '#00ff00';
$blue = '#0000ff';

echo $$color; //#ff0000 will be printed
$color = $_GET['color'];

$options = array(
  'red'   => '#ff0000',
  'green' => '#00ff00',
  'blue'  => '#0000ff'
);

echo $options[ $color ];
Sponsor our Newsletter | Privacy Policy | Terms of Service