0

I've just come across this piece of code:

// Assign initialized properties to the current object
foreach ($init as $property => $value)
{
    $this->{$property} = $value;
}

I don't undrestand why they use curly braces here. Whouldn't it be the same if it was written without them $this->$property = $value;?

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • @elclanrs, use answer to answer :^ ) – sectus Jan 20 '14 at 07:55
  • @sectus ... too funny elclanrs has 32k rep... prob knows when to use and not to use answer, lol. –  Jan 20 '14 at 07:57
  • 1
    There are a few dups, ie http://stackoverflow.com/questions/9056021/curly-braces-notation-in-php – elclanrs Jan 20 '14 at 07:57
  • possible duplicate of [Curly braces in string in PHP](http://stackoverflow.com/questions/2596837/curly-braces-in-string-in-php) – rccoros Jan 20 '14 at 07:58
  • Possible duplicate of http://stackoverflow.com/questions/2596837/curly-braces-in-string-in-php – rccoros Jan 20 '14 at 07:58
  • For a simple variable braces are not required, it's just convention I suppose. – elclanrs Jan 20 '14 at 08:02
  • 1
    Could be remnants from some code like `$this->{$property . "xyz"} = $value;`, or maybe the author just felt like the braces make it clearer (a stylistic thing). – Dagg Nabbit Jan 20 '14 at 08:03

2 Answers2

1

You are correct, it would be the same as if you did not have the curly braces. To me, this does not make sense to have them here. Normally, curly braces around variables are found in string literals to remove ambiguity.

For example,

$a = " $b->something says hello.";

This is ambiguous, because are you meaning to out put $b followed by "->something" or the "something" attribute of the object $b. Normally PHP works it out, but this is much better:

$a = " {$b->something} says hello.";

As the curly braces remove ambiguity.

Regards, Ralfe

ralfe
  • 1,412
  • 2
  • 15
  • 25
1

There's no advantage in your example, however it may have been used for consistency. Here's an example where you might use curly braces to ensure that PHP can parse what you are trying to do (access a dynamic property):

// Dummy object
$obj = new stdClass();
$obj->color = 'green';

// The dynamic property we want is slightly more complex
$tmp = array('wantProp'=>'color');

// ... so let's use curly braces
echo $obj->{$tmp['wantProp']};
itsmejodie
  • 4,148
  • 1
  • 18
  • 20