Passing By Reference & Passing By Value in PHP

I'm sure few people have heard about the term passing by reference.
Fun fact, I was one of those people.

Passing By Value

Assuming we have the function below in PHP

$country = "costaRica";
function travelInfo($country){
$country = "Togo";
}
//execute function
travelInfo($country);
echo( $country );

Without executing the code, what do you think will be the value of the variable $country?

I'm sure we're both correct on this one.

 

The value of the initial variable $country remains unchanged despite the reassignment within the function.

The method above is referred to as passing by value.

When we pass arguments by values, the argument, which is now a variable to that function will have function scope, hence, reassigning it does not change the value of the original variable. It will only create a local copy within the function.

Passing By Reference

Take a look at the code below

$country = "costaRica";
function travelInfo($country){
$country = "Togo";
}
//execute function
travelInfo($country);
echo( $country );

Now, what do you think will be the value of the $country variable?

 

The value of the variable will be reassigned to "Togo"

This is because, in the function, we defined our $country parameter to accept a value that is passed by reference only.

This is done using an ampersand operator [ ] before the parameter name.

Passing by reference also means that you have to provide a variable as an argument when invoking the function or PHP will throw an error. 

 

We're done with the explanation! Now, why don't we play with our code?

Let us create a function that will accept 2 parameters.
One will be passed by reference and the other will be passed by value.

Let me make sure you understand this concept.

$fromCountry = "France";
$toCountry = "USA";

function travelInfo($fromCountry, $toCountry){
    $fromCountry = "Nigeria";
    $toCountry = $toCountry;
}
//execute function
travelInfo($fromCountry, "Togo");
echo ( "I will travel far and wide from ".$fromCountry." to ".$toCountry );

Before you execute this code, can you guess the result? ?

 

Analysis

The function contains 2 parameters. One is passed by reference and the other is passed by value.

When you execute the code, providing a reference to the variable $fromCountry, as the argument passed by reference, its value will be reassigned within the function.

I hope you've understood how to pass variables by reference and how you can reassign a variable outside a function, from within a function.

Thank you for reading!


Simon Ugorji

16 Blog posts

Comments