PHP variable variables [closed]

-2

So I was studying a code here, and I came across a variable variable .

I've heard a lot about this concept but until today I still do not understand what they are for, when to use it etc.

So my questions are:

  • What are variable variables and what are they for?

  • Should we use Variable Variables ?, if so in what situations?

  • Variables of variables, have any effect on the performance of the php application?

If possible with examples.

    
asked by anonymous 25.08.2017 / 17:40

1 answer

3

Well I think you want to say variable variable and not variable variable

  • What are variable variables and what are they for?

A variable name that can be configured and used dynamically. A variable variable takes the value of a variable and treats it as the name of a variable.

  • Should we use Variable Variables ?, if so in what situations?

They are most useful when accessing values within a property that contains an array, when the property name is multi-part, or when the property name contains characters that are not valid (for example, json_decode () or SimpleXML).

I think the best example to understand its use is this:

<?php 
$varname = "foo"; 
$foo = "bar"; 

print $$varname;  // Prints "bar" 
print "$$varname";  // Prints "$foo" 
print "${$varname}"; // Prints "bar" 
?>

And for me at least, the greatest utility you have is when you have composite variable names, but that have part of the name equal to something, so you only put a list of the differentiation of these variables into a vector and with a foreach list all, as the example below shows:

<?php
// Given these variables ...
$nameTypes    = array("first", "last", "company");
$name_first   = "John";
$name_last    = "Doe";
$name_company = "PHP.net";

// Then this loop is ...
foreach($nameTypes as $type)
  print ${"name_$type"} . "\n";

// ... equivalent to this print statement.
print "$name_first\n$name_last\n$name_company\n";
?>
  • Variables of variables, have any effect on the performance of the php application?

Look at whether you have improved performance I do not know, but I do not think so, what I do know is that it has code optimization as demonstrated in the previous example.

All examples and exceptions you can find in the official documentation: link

    
25.08.2017 / 18:19