Max Koretskyi
Max Koretskyi

Reputation: 105499

what's the meaning of curly braces enclosing the variable name near $this

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;?

Upvotes: 0

Views: 435

Answers (2)

itsmejodie
itsmejodie

Reputation: 4228

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']};

Upvotes: 1

ralfe
ralfe

Reputation: 1454

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

Upvotes: 1

Related Questions