0

I have read this article about references in PHP.

PHP References: How They Work, and When to Use Them

I know its syntax but I'm a little bit confused on when to use references in PHP. Can you give me a real world example that I can apply references? Is it necessary to use references or I can just use a normal format of function? What is the real purpose of references?

Can you please explain this to me that I can easily understand.

Helen Andrew
  • 87
  • 1
  • 2
  • 12

1 Answers1

0

The reason for using references is so that you modify the value passed in to the function for instance.

Here's an example

$nameOfUser = "Mr. Jones";

function changeName($name) { // Not passing the value by reference
    $name = "Foo";

    return $name;
}

changeName($nameOfUser);

/**
 * The echo below will output "Mr. Jones" since the changeName() function
 * doesn't really change the value of the variable we pass in, since we aren't
 * passing in a variable by reference. We are only passing in the value of the
 * $nameOfUser variable, which in this case is "Mr. Jones".
 */
echo $nameOfUser;

$nameOfUser = changeName($nameOfUser);

/**
 * This echo below will however output "Foo" since we assigned the returning
 * value of the changeName() function to the variable $nameOfUser
 */
echo $nameOfUser;

Now if I want to get the same results in the second example above with references I would do it like this:

$nameOfUser = "Mr. Jones";

function changeName(&$name) { // Passing the value by reference
    $name = "Foo";

    return $name;
}

changeName($nameOfUser);

/**
 * The echo below will output "Foo" since the changeName() function
 * changed the value of the variable we passed in by reference
 */
echo $nameOfUser;

I hope that my examples were understandable and that I have given you a better insight to how references work.

I don't have an example of when you would need references since I personally think it's better to return the value and set it that way. Modifying variables passed in to a function can confuse the user that uses the function.

Marwzoor
  • 36
  • 4