Advanced Variables and Using Them by Reference in PHP


Variables by Reference

Variables can also hold their value as a reference to another value. This means, a variable simply points to another variable. So whatever value the other variable holds, the reference variable also holds the same. For reference assignment we use an ampersand sign (&) after the equals to sign (=) while assigning a variable.

Example:

Notes:

  • See how the updated value of $var1 is printed when we output $var2.
  • If we hadn’t used the ampersand sign, then $var1 would hold the value “Ashish” till the end.
  • If we unset the value of $var1, $var2 will still hold the latest value.

Using Reference Variables in Functions

We can pass in variables in PHP as arguements. When we use reference variables, they are passed and updated by the function. To pass a variable by reference, place the ampersand sign (&)in front of the arguments passed in a function.

Example:

Notes:

  • See how the value of the variable $value is updated by the function since it is passed by reference.
  • $var and $a points at the same thing.

Variable Variables

There’s an interesting way to set variables in PHP. A variable value can be another variable name. So, you will be using variable variables. Two $ signs are used for such purpose. This is used when we do not know the name of the variable. It sounds complicated, so here’s an example:

Note:

  • There are two $ (dollar) signs.
  • $var = name, so $$var = $name and $name happens to hold the value “Ashish”.

The same “Variable Variables” can also be used in arrays. But in arrays it can be confusing when we use two dollar signs. Like when we use $$name[0], the array position [0] makes it confusing and we might. Should we take the position of the array first or the $$variable first. For this issue, we can use curly braces to separate which comes first, just like in maths.

Example:

You may also like

Comments are closed here.

Advertisements

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2 other subscribers