PHP Pass Arguments by Reference

PHP Pass Arguments by Reference

Last Updated on Jan 12, 2023

Introduction

By default when we pass argument to a function we pass it by value which means if we change the value inside the function it won't affect the value outside of the function.

For example in the following code, outside the function the value of a is still 2.

function changeMyNumber($number){
    $number = $number + 10;
    return $number;
}
$a = 2;
$b = changeMyNumber($a);
echo $a; // 2
echo $b; // 12

But what if we wanted our function to have the ability ot change the original variable as well? then we should pass that argument by reference. which means we are passing its pointer to the function and whenever we change that variable instead looking at its name we will check its reference (its pointer) and change that.

Argument Reference

In order to pass the argument by reference we need to prepend an ampersand (&) to the argument name when we are defining our function. like this:

function nameOfTheFunction(&$arg){
    // do something with the argument
}

so if we wanted to actually change the value of a as well in our first example our function would be like this:

function changeMyNumber(&$number){
    $number = $number + 10;
    return $number;
}
$a = 2;
$b = changeMyNumber($a);
echo $a; // 12
echo $b; // 12

so now the value of a changes even outside the function.

It is a great feature but it can also get very tricky. it's good to know that some of the built in functions also get the reference of the argument. for example when we want to sort an array it sorts the original array so we need to be careful.

Conclusion

Now you know how to pass arguments by reference in PHP.

I recommend you to open a PHP files and try to define multiple functions. some of them would get the value of a variable and some would get the reference of the variable.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • Pass arguments by Reference
  • Reference vs Value in function arguments

Category: programming

Tags: #php #tips and tricks

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

Courses