2

From what I can tell in the PHP Manual, it doesn't seem like there is much difference between defining a variable variable with double brackets or double dollar signs.

$foo = 'hello';
$$foo = 'hi';
echo $hello; // 'hi'

$baz = 'goodbye';
${$baz} = 'bye';
echo $goodbye; // 'bye'

The only difference it mentions in the manual is when using arrays. Is there any other noticeable difference between the two? Which one is better for which situations?

2 Answers 2

1

Both versions are basically the same.

The curly braces notation is used in cases where there could be ambiguity:

$foo = 'bar';
$bar = [];
${$foo}[] = 'foobar';

var_dump($bar); // foobar

If you'd omit the braces in the above example, you'd get a fatal error, with the braces, it works fine.

However, I would recommend avoiding dynamic variable names altogether. They are funny to use and may save some space. But in the end, your code will become less readable and you will have trouble debugging.

Sign up to request clarification or add additional context in comments.

Comments

1

In this case, there is no difference. It is like using parentheses to group operators, even when they are not necessary.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.