What is a Reference in PHP


What is a Reference in PHP?
A reference is an alias of a variable. PHP supports references in a very similar way as the Perl language. Here are some basic rules about using references in PHP:

To create a reference of given variable, you need to use the reference operator: &.
For example, &$title creates a reference of variable $title.

Reference can be assigned to another variable using the assignment operator: =.
For example, $subject = &$title assigns the reference of variable $title to variable $subject.

The variable holding the reference is an alias of the original variable and behaves the same way as the original variable.
For example, $subject = &$title; var_dump($subject); prints information of the data assigned to variable $title.

If the original variable is assigned to a new data, the reference variable is automatically assigned to that new data.
For example, $subject = &$title; $title = “New String”; assigns “New Sting” to both $subject and $title.

If the reference variable is assigned to new data, the original variable is automatically assigned to that new data.
For example, $subject = &$title; $subject = “New Text”; assigns “New Text” to both $subject and $title.

Multiple reference variables can be created by assigning the reference to multiple variables.
For example, $subject = &$title; $topic = &$title; assigns the reference of $title to both $subject and $topic.

Actually, original variable and its reference variables can all be viewed as references to the assigned data shared by all of them.
For example, $subject = &$title; $topic = &$title; $topic = “New Message”; creates 3 variables referring to the same data “New Message”.

To remove the reference link between a variable and its assigned data, you need to use the unset($var) function.
For example, $title = “New String”; unset($title); removes the reference link between $title and “New String”. $title is the “unset” states now.

If multiple variables are referencing the same data, removing the reference link on one variable does not affect other variables.
For example, $subject = &$title; $topc = &$title; $topic = “New Message”; unset($topic); removes the reference link on $topic, but $subject and $title are still referring to “New Message”.

If multiple variables are referencing the same data, assigning a new reference to a new data to one variable does not affect other variables.
For example, $subject = &$title; $topic = &$title; $topic = “New Message”; $topic = &$name; assigns the reference of the $name to $topic, but $subject and $title are still referring to “New Message”.

Now let’s take an example to confirm some rules mentioned above.
Click here to download the example file.
What is a Reference in PHP What is a Reference in PHP Reviewed by Abdul iTech on Sunday, March 03, 2019 Rating: 5

No comments:

Powered by Blogger.