Homunculus Reticulli
Homunculus Reticulli

Reputation: 68476

Why are curly braces around a variable inside of a double quoted string not treated literally?

I am writing a trivial templating system for running dynamic queries on a server.

I originally had the following code in my templating class:

$output = file_get_contents($this->file);

foreach ($this->values as $key => $value) {
    $tagToReplace = "{$key}";
    $output = str_replace($tagToReplace, $value, $output);
}

I notice that the strings were not being replaced as I expected (the '{}' characters were still left in the output) .

I then changed the 'offending' line to:

$tagToReplace = '{'."$key".'}';

It then worked as expected. Why was this change necessary?. Does "{" in an interpreted string have special significance in PHP?

Upvotes: 0

Views: 323

Answers (2)

dorsh
dorsh

Reputation: 24740

Yes. When using double quotes, "{$key}" and "$key" are the same. It's usually done so you can expand more complex variables, such as "My name is: {$user['name']}".

You can use single quotes (as you have), escape the curly brackets -"\{$key\}"- or wrap the variable twice: "{{$key}}".

Read more here: http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing

Upvotes: 6

mauris
mauris

Reputation: 43619

Yes. It does help to resolve variable names. Take a look at this question.

{ and } can used as follow:

$test = "something {$foo->awesome} value.";

By the way, you can further improve your code by using the following (and thus avoiding the situation you're having right now):

$output = file_get_contents($this->file);
$output = str_replace(array_keys($this->values), $this->values, $output);

Upvotes: 1

Related Questions