Reputation: 32721
I am wondering what { } in the following. What { } is doing here? $this->{$key} = $value;
Thanks in advance.
In one file
$config['field']['calendar'] = array('type'=>'boolean');
$config['field']['category'] = array('type'=>'boolean');
$config['field']['customers'] = array('type'=>'boolean');
...
$this->preference_form->initalize($config);
And in Preference_form.php
function initalize($config = array())
{
foreach($config as $key => $value)
{
$this->{$key} = $value;
}
}
Upvotes: 0
Views: 89
Reputation: 8301
It's escaping the variable expression so that the member can be set dynamically.
Take a look at the documentation here: http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex
Upvotes: 0
Reputation: 55271
They're optional in this case, but it's a way of making it clearer to the reader (and the parser) that you're referring to a variable.
http://www.php.net/manual/en/language.variables.variable.php
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
Another case where this syntax is useful is when expanding a function call in a string.
This doesn't work (or rather it'll evaluate $someObj
as a string, and then append ->someFunc()
:
$myString = "$someObj->someFunc()";
But this does what you'd expect:
$myString = "{$someObj->someFunc()}";
Upvotes: 1