user163408
user163408

Reputation:

Is there any differences between $var and ${var}

Are these 2 two "spellings" equivalent? Just wondering.

Upvotes: 1

Views: 97

Answers (2)

Constantine Loukas
Constantine Loukas

Reputation: 292

Pretty much. The only difference is that you can enter code to be parsed in between the curly braces to get "variable" variable names.

Ex.

${'t'.'e'.'s'.'t'} = 'test'; // is the same as $test = 'test';  
${substr('testaaa',0,4)} = 'test'; // the same

You can even do something like:

${ 'a' == 'b' ? 'Foo' : 'test' } = 'test'; //the same

It is essentially the same as:

$var_name = substr('testaaa',0,4);
$$var_name = 'test';

Upvotes: 1

zerkms
zerkms

Reputation: 255025

${var} out of context could be either correct or not. If it is used inside of the string like "foo ${var} bar" - then it is the same.

If it is used right in the code - then ${var} is incorrect, and ${'var'} should be used instead.

The valid cases for using ${...} are:

  1. Inside the string in cases like "ab${cd}e" - when all the letters go without spaces, "${a['b']}" - when you use it with arrays

  2. When you want to assemble the variable name dynamically: ${'a_' . $i}

Upvotes: 6

Related Questions