Double dollar sign php
Solution 1
The problem with $$ in PHP is that you create unknown variable names, that may override variable names you already use. It is a source for subtle programming errors, and should generally not be used.
Solution 2
Well, you could just use extract()
function. Also that fragment: get_object_vars($this->view)
indicates that you should rather have some array to store those variables, not an object.
Solution 3
Nope, that's the way to do it and the only way if I'm not mistaken. Though my question would be to ask why you'd want to do that instead of using the object variable.
Slavic
I know a few things about the Internet and how to make websites.
Updated on July 23, 2022Comments
-
Slavic almost 2 years
Possible Duplicate:
What does $$ (dollar dollar or double dollar) mean in PHP?I found myself using this kind of code in one of my controllers:
foreach(get_object_vars($this->view) as $property=>$value){ $$property = $value; }
Is there any problem with using the $$property to "localize" view properties into simple $variables?
edit:
I should add that this code is run in the scope of a view-specific method, so there's no problem of overriding local variables. This is to divert some of you guys from pointing out the problem of overriding local variables.
-
Slavic over 13 yearsThat's because I supply the values to a view script, which accesses much more elegantly values in $value fashion, rather than $this->value fashion.
-
Slavic over 13 yearsExtract only works for arrays. The reasons I'm using an object is because of the underlying code structure. I don't see a problem in using get_object_vars();
-
NikiC over 13 yearsAnd probably you want to extract skippingly, so no variables are overwritten.
-
Slavic over 13 yearsThanks, makes sense. However, if I use it within the context of the the view object, where the only properties are the values to be accessed by the view script, i still tihnk one can freely use it.
-
Lotus Notes over 13 yearsI disagree with this answer. If you are using this in a View object then you're in a limited scope. The $$ is only a problem if you're always working in global scope which you aren't doing if you're using an MVC structure. If your View object really needs some 'reserved' variables that you don't want overridden, name it something like
$_var
so you won't accidentally override it. -
Erik over 13 yearsThat's why I wrote "generally". Slavic seems to know what he's doing.
-
greenoldman about 9 yearsPowerful, not powerful, but from the linked question it seems it is just shortcut to (simple form)
eval
. Does it do anything beyond that?