The principle is (sort of) OK, but the code isn't quite right.
Code: Select all
<?php
// no array flipping needed
foreach($_POST as $key=>$value)
{
$this->$key = $value;
}
?>
In the same way that you can declare a class property with $this->var = 'value'; you can declare a whole bunch in a loop. Referencing isn't involved.
It can seem like a neat way to do it but there are issues.
It's possibly better to make the effort to name the vars explicitly so you can see at a glance what properties are being declared when you come back to read the code at a later date and have forgotten what was in the form.
Also, auto-extracting user input can be extremely dangerous. A forged form could add any var with any value to the $_POST array and an extract() or a foreach() loop like the above instantly declares them all in your script, possibly overwriting other vars with the same name and in the same scope as the extract/foreach code or setting values for undefined vars.
Inside a function, often the first thing you do is get the POST values and, if so, there isn't anything else in the fn scope to overwrite at that point* (if NOT you're in trouble). Later on, your script would itself overwrite any poisoned POST vars. Assuming you don't have any undefined vars (E_ALL.. ) you'd be safe.
*
apart from the fn args, if there are any
However, inside a class, properties have a kind of "global class scope" and so auto-extracting user input as properties carries a greater risk. It's likely that a bunch of properties have already been declared and are sitting around, just waiting to be poisoned.
In saying that, I do sometimes do it myself. For example, it's convenient when you're developing and haven't yet finalised all the form elements.
Also, you mentioned that you have checked the POST array beforehand. If you have some kind of "alien key" check as part of that process you would pick up an attempt at variable substitution by adding new keys to the POST array. That lets you be sure you're extracting just the $keys you expect - although of course you still can't assume their values are good.[/i]