Jump to content

Simple Dynamic Variable Example


jaunty_mellifluous
 Share

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
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?

Link to comment
Share on other sites

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++;

Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • 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.