What’s the difference between $var and $var?

Asked

Viewed 392 times

5

What is the difference between a $var variable and $$var in PHP? How can it be used? You can cite some examples of use?

  • Related: http://answall.com/questions/38427/para-que-servem-as-chavetas-numa-string-sql-em-php/38439#38439

1 answer

5


$var is a variable and $$var is a "variable variable" whose name is the value of $var.

take the example:

<?php

    $var = "hoje";
    echo $var;
    $$var = 'ontem';
    echo $hoje;
?>

Use $$var is not very common (hardly see use in applications) but I’ve seen it once: the creator of the code had used to create variables dynamically with the name of the $_GET array key.

consult:

http://php.net/manual/en/language.variables.variable.php

http://php.net/manual/en/functions.variable-functions.php

http://php.net/manual/en/language.oop5.basic.php

  • What are the advantages of using a variable like this? If any...

  • @Paulocosta, edited with the use.

  • 1

    @Paulo, the advantage is when you need to create variables dynamically. The name of this is "variable". The same scheme can also be used to create or call functions, methods and objects, depending on the PHP version.

  • @Danielomine which versions would be these?

  • 2

    Don’t worry too much about the version. Variable variables are available since before version 5. Variable methods (class functions) and variable instances (new class(), depend on more recent versions. But if you have PHP 5.3 at least, which is already quite old, they are already available. I can’t say for sure the correct version, but there’s not much to worry about. See the manual for details. I inserted the links in Ricardo’s reply.

  • This is another gambiarra offered by PHP. Do not use, my friend searched for a variable in the system for a week and did not find. When he went to see the guy he had used this "variable"

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.