-2

I'm learning how to use $$ in PHP, but I'm stuck trying to fix this code.

<?php
    $now_test = 0;
    print_r($now_test);
    $item = 'test';
    $now2 = ('$now_'.$item);
    echo $now2;
    print_r($$now2);
?>

The first print_r shows me a 0, an expected value. Later, I merged '$now_' and $item, and test with echo, so I can see that $now2 = '$now_test'. But the final statement, the print_r($$now2) won't work, why? I really don't understand it.

Thanks a lot!

Tak-MK
  • 28
  • 1
  • 9
  • 1
    Use `$now2 = 'now_'.$item;` instead of `$now2 = ('$now_'.$item);` – Bora Jul 03 '14 at 07:31
  • 3
    Please just don't use variable variables in php. They're terrible. – halloei Jul 03 '14 at 07:34
  • Why are they terrible? P.S.: And why people downvoted me? It's only a simple PHP question... – Tak-MK Jul 03 '14 at 07:38
  • [Here](http://stackoverflow.com/a/2778797/3318377) an answer why not to use them. And the simplicity of the question may be the reason for the downvotes. – halloei Jul 03 '14 at 07:44
  • 1
    @TakuyaMK: The answer to this question was something you could've found by looking at the manual, first. I think that's why people voted your question down. Variable variables are, indeed, terrible, because they clutter your namespace with variables, make code insanely hard to debug, while also making your code more error-prone. If, in your example `$item` was re-assigned later on down the line to `'foo'`, `print_r($$now2);` would create a new variable called `now_foo`, and _not_ work as expected anymore – Elias Van Ootegem Jul 03 '14 at 07:45
  • @TakuyaMK: variable variables are _evil_. Think of what you're doing here as syntactic sugar for `eval($now2 = $now_'.$item.';');`. The result/behaviour is exactly the same. Of course `eval` is pure _evil_, which means that variable variables are, by definition, evil, too – Elias Van Ootegem Jul 03 '14 at 11:21

2 Answers2

1

Demo

The problems are;

  1. Do not use paranthesis
  2. Use 'now_'.$item instead of '$now_'.$item

You can use following;

<?php
    $now_test = 0;
    print_r($now_test);
    $item = 'test';
    $now2 = 'now_'.$item;
    echo $now2;
    print_r($$now2);
?>
Hüseyin BABAL
  • 15,400
  • 4
  • 51
  • 73
0

I know this works:

<?php
$now_test = 0;
print_r($now_test);
$item = 'test';
$now2 = ('now_'."$item"); //NO $ in string
echo $now2;
print_r(${$now2}); //added braces around $now2
?>

you were missing the curly braces and also you needed to ommit the $, changes have been commented

JB567
  • 1