Jump to content

Simple Dynamic Variable Example


jaunty_mellifluous

Recommended Posts

<?php 

$foo = 5; 

$too = 7;

${"foo"}++; 
${"too"}++;
echo $foo;
echo '<br />' . $too;

$my_var_name = "foo";

${$my_var_name}++;

echo $foo;
    
?>

 

I understand the part that $my_var_name is going to increment $foo. But I don't understand that when we used ${"foo"} we did not add the $ sign with it. But when we use ${$my_var_name} we have to add another $ sign. why is that?

Link to comment
https://forums.phpfreaks.com/topic/214702-simple-dynamic-variable-example/
Share on other sites

No, I'm just talking about the $ sign in ${$my_var_name} earlier in the program when the dynamic function is called as ${"foo"} it's purpose is to increment foo right.

 

But when $my_var_name is made equals to $foo and when it is called to be incremented we add an additional ${$my_var_name} to it inside the parenthesis. While before with foo we did not do that.

 

So that is what I was asking about, why is that so?

Because "foo" is a string and you are defining a var using that string as the name.  $my_var_name is a variable that contains a string and you are using the string contained in that var as the variable name.

 

//this:
${"my_var_name"}++;
//would be the the same as this:
$my_var_name++;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.