Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable variables in PHP - What is their purpose? [duplicate]

In PHP there's a functionality officially called "Variable Variables" where one can assign variable variables. A variable variable takes the value of one variable as the name for a new variable! For example:

$name='Joe';
$$name='Smith'; // could also be written as ${$name}='Smith'

The first variable $name contains the value 'Joe', while the second is variable named $Joe with the value 'Smith'. Take into account that PHP variables are case-sensitive!

I've never used this functionality and do not see the purpose for that. Could someone explain to me where this functionality could be exploited as a good practise?

like image 515
sbrbot Avatar asked Aug 31 '14 14:08

sbrbot


3 Answers

This has some uses when referencing variables within classes, and there are some cases where these can actually be required (such as in __get(), __set(), __isset(), and __unset()). However, in most cases it is unwise to use them on global variables.

Be aware that you should NEVER directly accept end-user input when it comes to variable variables. Instead a wrapper function should be used to ensure that only specific inputs are allowed.

In most cases, variable variables are not required, and it is recommended that you avoid them when possible.

like image 163
Nicholas Summers Avatar answered Oct 14 '22 07:10

Nicholas Summers


You can use for something like

$labels = array( 'first_name" => 'First Name", 'middle_name" => 'Middle Name", 'last_name" => 'Last Name", 'phone" => 'Phone");
        foreach($labels as $field => $label)
        {
        echo '<div id='field'><label for='$field'>$label</label>
        <input id='$field' name='$field' type='text' value='".$$field."' /></div>";       
        }

In my opinion is bad old school...

like image 40
SylarBg Avatar answered Oct 14 '22 06:10

SylarBg


Sometimes we need software that is extremely flexible and that we can parametrize. You have to prepare the whole thing, of course, but part of it just comes from user input, and we have no time to change the software just because the user needs a new input.

With variable variables and variable functions you can solve problems that would be much harder to solve without them.

Quick Example:

Without variable variables:

$comment = new stdClass(); // Create an object

$comment->name = sanitize_value($array['name']);
$comment->email = sanitize_values($array['email']);
$comment->url = sanitize_values($array['url']);
$comment->comment_text = sanitize_values($array['comment_text']);

With variable variables

$comment = new stdClass(); // Create a new object


foreach( $array as $key=>$val )
{
    $comment->$key = sanitize_values($val);
}
like image 12
Faiz Ahmed Avatar answered Oct 14 '22 07:10

Faiz Ahmed