Jump to content

{ And }


sneskid

Recommended Posts

I read that "Sometimes PHP programmers need to use "{" and "}" to resolve ambiguity"
The example wasn't enough.

I'm currently going through someone elses code, and they use {} in the following syntax

// this code is part of a class function called "urldecodeRecursively"
$d = new stdClass();
foreach ($data as $key => $val)
{
if ($key != urldecode($key)) {
[b]$d->{urldecode($key)}[/b] = $this->urldecodeRecursively($val);
}
else {
[b]$d->{$key}[/b] = $this->urldecodeRecursively($val);
}
}
return $d;
//

I'm just curious about the $d->{stuff}
Could someone shed some light on that?

thanks.
Link to comment
https://forums.phpfreaks.com/topic/13170-and/
Share on other sites

The { and } are used to basically help PHP out, otherwise it'll get confused. So if the code was this:
$d->urldecode($key) = $this->urldecodeRecursively($val);

PHP will try to called a function called urldecode inside the stdClass. Which probably doesnt exist and end up causing an error! But we want to use a pre-defined PHP function called urldecode instead. So we use the curly brakets to define the function we want to use.

The same applies to this code:
$d->{$key} = $this->urldecodeRecursively($val);
But instead of calling a function we want to use the [b]value[/b] of the $key variable. So if $key was set to [b]SomeVar[/b], $var will be replaced with its value when it is parsed like so:
$d->[i]SomeVar[/i] = $this->urldecodeRecursively($val);

Hope that helps. Basically { and } are used to define functions/variables
Link to comment
https://forums.phpfreaks.com/topic/13170-and/#findComment-50755
Share on other sites

wildteen's got it exactly right... i like to think of it like this: the brackets allow you to [b]force[/b] PHP to translate the values inside them first. that's why sometimes, when we want to create a variable named from the value of another variable, we use the brackets, too:
[code]
$string = "obsidian";
${$string} = "me";
echo $obsidian; // outputs "me"
[/code]

it's not exactly the most simple concept to grasp, although it is a very helpful one to get ahold of.
Link to comment
https://forums.phpfreaks.com/topic/13170-and/#findComment-50789
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.