Is there anything wrong with doing this? Ive looked everywhere and it doesnt seem like this is a common thing? is there a built in function im not aware of that does this? Im using PDO for inputs so I am assuming this is fine.
thanks for ANY help!!
foreach($_POST as $post => $var){
${$post} = $var;
}
Warning
As #Gumbo stated, this is, in no way, what you want to do. You
should avoid doing anything like this with super globals in any sense.
You're better off controlling each aspect as best as possible and
assigning the variables properly, as best practice permits. i.e.
$a = 'derp';
What you're doing is called Variable Variable and is built into PHP. It essentially allows you to dynamically create variables for use within the current scope.
Take a $_POST array of the following:
Array (
[a] => 'derp'
)
Now with your current code, you'll be dynamically creating & assigning a variable:
foreach($_POST as $post => $var){
${$post} = $var;
}
Which in turn, allows you to access said variable as the key:
echo $a; // would echo out derp
From personal experience, this isn't always necessary and an issue you could potentially run into is overwriting a variable that has already been set, in turn, producing unwanted/unexplained output.
You'd be best to have a read of these answers to gain a wider understanding of what you're currently doing:
Dynamic variable names in PHP
PHP Variables - Concatenate variable name
php variable variables problem (especially worth a read if trying to harness superglobals)
Related
One thing I find myself often wanting to do is convert a large associative array, usually from a POST request (a registration form, for example, with many inputs) into local variables based on the key from the array. If you are using the values from the array often, your code quickly becomes littered with long variable names and quotes.
To prevent this for small associative arrays, it is acceptable to just do something like this:
$username = $_POST['username'];
$password = $_POST['password'];
I'm not escaping them for this example to keep everything as uncluttered as possible, so relax.
You can also do this:
list($username, $password) = $_POST;
But what if the $_POST array is larger? Then it becomes tedious to do both of those methods. To fix that, you can run a loop like this:
foreach($arr as $key => $value)
{
${$key} = $value;
}
The problem with this method is that it assigns local variables. It would be nice if it were possible to call a function in a parent class that runs this loop and those local variables were accessible within the calling class. Imagine an MVC setup where every controller is derived from a Controller class, and likewise for the models. It would be nice to do:
$this->localize($_POST);
doWhatever($username) // $username works! Assuming $_POST['username'] is defined
Creating such a method causes the local variables to only remain within the scope of the localize() function in the parent class, so this won't work. What I have been doing is running the same loop with one modification:
foreach($arr as $key => $value)
{
$this->{$key} = $value;
}
This works and all, but doesn't really solve the initial problem. Instead of code that is cluttered with brackets and quotes, it has $this-> all over the place, not to mention it is assigning variables that were never formally defined within the class.
So finally, my question: is it possible to create a function such as the localize() I described, such that it can be inherited from a parent class but create local variables relative to the child class ($username instead of $this->username).
Also, whether you can or not, is this considered bad practice? It seems a bit hacky to me, and you are ignoring some principles of OOP. If it is, do you use a solution to fix the ugliness and clutter of large associative arrays, or do you just deal with it?
The PHP extract function does exactly this. Extracts a hash into the local namespace:
http://us3.php.net/extract
An important addendum:
Be sure to use the EXTR_SKIP option for extract() if the function is acting on user-supplied variable names (such as provided by $_POST) to prevent redefining of existing variables:
$myvar = 'abc';
extract($_POST, EXTR_SKIP); // $_POST['myvar'] won't overwrite $myvar.
It's a bad practice, users will be able to redefine any of your variables just by passing key in POST array, it's pretty simple and it's how register_globals works, and it's why this ability is deprecated in 5.3 and removed in 5.4.
I have code where I use some variables. Example:
$name = "someName";
$output = sprintf($doingText, $name); // $doingText is here undefined
I want to search the code for surely undefined variables (some sort of static code analysing).
These variables should be all some language text. No problem until there, but I don't want to make manually a list which variables exist: I want to get the variable names and then make some html form where I can see them and put into database in variablename-text pairs.
Question is: how to search them? (I haven't found any script which is able to do this in PHP by googling...)
(p.s.: I don't know what is the best method to search them as there may not be only assignments by =, but also with foreach ($arr as $val) etc.)
Why not use an IDE like NetBeans? That will actively check if you have unused variables. So while your coding it will show you in real time, rather then finish the script and find out you have x amount of errors/unused variables. Just food for thought.
In PHP is wrong to cast $_REQUEST to an object to manage it more easily?
$request = (object) $_REQUEST;
if(isset($request->submit) && isset($request->text) && !empty($request->text))
{
// Do stuff
}
EDIT: i mean any unexpected side effect?
I would say there's nothing wrong with this except obviously the little added time you'll get. What I would do though is run the $_REQUEST array through a cleaner function to validate and clean up the variables. This way you can always know that if your using the object version of the $_REQEUST that it's safe to use.
Update
I would go as far as saying this is probably best practice in the world of modern web applications. I mean look at the MVC frameworks you use (Zend, CodeIgniter, CakePHP etc) they all clean the $_REQUEST, $_GET, $_POST, $_SERVER etc and convert them to objects.
Remeber that the overhead on something like this would be so minimal you wouldn't even notice it. The time PHP takes to parse and output a page is so small, usually smaller than a DOM request for one image.
Nothing I can see that is wrong with that.
It will just allow you to access the associative array as an object.
Not to be argumentative but I don't see how this makes it any easier to manage the $_REQUEST variable. You could write the same line of code like so:
if(isset($_REQUEST['submit']) && isset($_REQUEST['text']) && !empty($_REQUEST['text']))
{
// Do stuff
}
Also, there can be some issues with array keys that don't translate into object property names properly. Take for example $_REQUEST['var name']. Completely legitimate array name but translate the array into an object and you'll be sorely disappointed at the results.
However, if you trust your users that much and want to spend the extra clock cycles creating a new object you could always brute force it.
$request = new stdclass;
foreach($_REQUEST as $field => $value){
$request->$field = $value;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What's an actual use of variable variables?
i saw the concept of variable variables in php .
that is a variable whose name is contained in another variable .
like this
$name = ’foo’;
$$name = ’bar’;
echo $foo;
// Displays ’bar’
one advantage that i see is , you can create variable names with numbers or lettes which you can not use normally . like this
$name = ’123’;
/* 123 is your variable name, this would normally be invalid. */
$$name = ’456’;
// Again, you assign a value
echo ${’123’};
// Finally, using curly braces you can output ’456’
and also you can call some functions like this
function myFunc() {
echo ’myFunc!’;
}
$f = ’myFunc’;
$f(); // will call myFunc();
and in a book i saw this
Variable variables are a very powerful tool, and should be used with
extreme care, not only because they can make your code difficult to
understand and document, but also because their improper use can lead
to some significant security issues.
The problem i have is if using variable variables in the code can be that dangerous . why are we using it . and is there any major advantages using variable variables in my code , if any what are those advantages .
you can use it in case of not-user-input. Look
function getVar($gid){
$name = "gid".$gid;
global $$name;
$var = $$name;
return $var;
}
It's useful when you have a lot of variables (same start with ending number, etc...) which is probably save
Look at your example:
function myFunc() {
echo ’myFunc!’;
}
$f = ’myFunc’;
$f(); // will call myFunc();
It is powerful: $f can have a value dynamically and the function called based on this value.
At the same time: If the user was given limitless access to $f this could be a security threat
In some MVC Frameworks they use it to run a function which will vary depending on the URL:
http://www.domain.com/thecontroller/theaction
in PHP side they will parse the url, get the second segment which is the name of the function then run it, but how? they will assign to a variable like what you have mentioned:
$toRun = 'theaction';
$toRun();
I've used double and even treble indirect pointers in C, but have never explicitly used variable variables in PHP (but I have used variable functions and classes).
I think it's somehow reassuring that there's more functionality in PHP than I use - and that I can make informed choices about which constructs I do use (I often use explicit references for example).
A nice usage I saw in some framework is using them to access, easier, values passedfrom another script as an array:
$array['test'];
$array['other'];
$array['third_index'];
// or simply $array = array('test','other','third_index');
foreach($array as $k=>$v)
{
$$k = $v;
}
So you could then have $test, $other and $third_index being usable as variables. Pretty handy when dealing with views, for example.
Solution?
Apparently there isn't a faster way, I'm okay with that.
I am just learning php and I am trying to figure out some good tips and tricks so I don't get into a bad habit and waste time.
I am passing in values into a php script. I am using $_GET so the URL looks like this:
/poll_results.php?Sports=tennis&cat=Sports&question=Pick+your+favorite+sports
Now I know how to accept those values and place them into variables like so:
$sports = $_GET['Sports'];
$cat = $_GET['cat'];
$question = $_GET['question'];
Super simple yet if I am passing 5 - 6 things it can get bothersome and I don't like typing things out for every single variable, that's the only reason. I know there is a better way of doing this. I have tried list($var, $var, $var) = $_GET but that doesn't work with an associative array just indexed ones (i think).
I also tried variable variables like so:
foreach($_GET as $value) {
$$values = $value;
echo $$values;
}
But that gave me a Notice: Undefined variable: values in poll_results.php on line 14. Line 14 is the $$values = $value. I don't know if that's a big deal or not... but I'm not turning off error reporting as I am still in the process of building the script. It does do what I want it to do though...
Any answers will be copied and pasted into my question so the next person knows :D
Thanks guys!
Your second bit of code is wrong. It ought to be like
foreach ($_GET as $key => $value) {
$$key = $value;
}
if i understand your intent. However, you're basically reinventing register_globals, which....eh. That'll get ya hacked.
If you have certain variables you want to get, you could do like
foreach (array('Sports', 'cat', 'question') as $key)
{
$$key = $_GET[$key];
}
which is less likely to overwrite some important variable (whether by accident or because someone was messing around with URLs).
Use parse_url() to extract the query string from a URL you've got in a string, then parse_str() to extract the individual arguments of the query string.
If you want to pollute your script with the contents of the superglobals, then you can use extract(). however, be aware that this is basically replicating the hideous monstrosity known as "register_globals", and opens all kinds of security vulnerabilities.
For instant, what if one of the original query arguments was _GET=haha. You've now trashed the $_GET superglobal by overwriting it via extract().
I am just learning php and I am trying to figure out some good tips and tricks so I don't get into a bad habit and waste time.
If I am passing 5 - 6 things it can get bothersome and I don't like typing things out for every single variable, that's the only reason.
What you are trying to do will, unless curbed, become a bad habit and even before then is a waste of time.
Type out the variables: your digits like exercise and your brain can take it easy when it doesn't have to figure out which variables are available (or not, or maybe; which would be the case when you use variable variables).
You can use
foreach($_GET as $key => $value)
To preserve the key and value associativity.
Variable variables (the $$value) are a bad idea. With your loop above say you had a variable named $password that is already defined from some other source. Now I can send $_GET['password'] and overwrite your variable! All sorts of nastiness can result from this. It's the same reason why PHP abandoned register_globals which essentially does the same thing.
My advice: use $_POST when possible. It keeps your URLs much cleaner for one thing. Secondly there's no real reason to assign the array to variables anyway, just use them where you need them in the program.
One good reason for this, especially in a large program, is that you'll instantly know where they came from, and that their data should not be trusted.