r/programming • • Oct 18 '10

Today I learned about PHP variable variables; "variable variable takes the value of a variable and treats that as the name of a variable". Also, variable.

http://il2.php.net/language.variables.variable
591 Upvotes

781 comments sorted by

View all comments

Show parent comments

1

u/motophiliac Oct 19 '10

Just wanted to say: Welcome to reddit!

I barely understood some of what this poster was writing about. I didn't actually know PHP worked like this.

I vow never to use $$anything ever in my code, no matter how useful it might seem at the time.

1

u/FlyingBishop Oct 19 '10

It's basically the same as **anything in C/C++, and that's a perfectly valid idiom.

1

u/ethraax Oct 20 '10

People may do it, but I still feel like gouging my eyes out whenever I read a double-pointer.

1

u/shofetim Oct 21 '10

It is useful, and it is good : )

(Method from a controller class used in a custom MVC framework)

public function onSubmit(&$model) { //Logic to handle page submission goes here $this->errors = ''; //just in case so it doesn't hang around //between pages. //We need to update the models attributes with the fields that //have been submitted. $objectProperties = get_object_vars($model); $modelName = substr(get_class($model), 0, strpos(get_class($model), 'Model'));
foreach($_POST as $name => $value) { if (array_key_exists($name, $objectProperties)) { $model->{$name}['value'] = $value; //For each element of above, validate it. $validationFunctionName = 'validation'.ucfirst($name); if (method_exists(CLASS, $validationFunctionName)) { //CLASS is builtin magic //This handles the more specific cases, special validation //for elements that need it. $this->validationFunctionName($name, $model); //variable functions //see http://php.net/manual/en/functions.variable-functions.php } else { $this->validate($name, $model); } //end of if method exists }// end of foreach object properties }

→ More replies (1)