Passing and returning variables by reference in PHP

In this tutorial I will show you how to pass and return variables by reference in PHP.

Normally when we assign the value of one variable onto another we are assigning a 'copy' of the former onto the latter and the 2 variables are in no way linked to each other, they simply, at the time of assignment, contain the same value. Any changes made to the value of either variable later on in the script will be of no effect to the other.

By using the 'by reference' feature of PHP we can make the left hand operand of an assignment operation be an actual reference to the right hand operand as opposed to just a copy of! This means that any changes made to the right hand operand later on in our script will be reflected in the left hand operand also. We use the special '&' prefix on our variable that we are declaring as 'by reference'.Consider the following:

We can also pass a reference to a variable into the argument of a function! This allows us to modify external variables from within the function as follows.

It may also be usefull to return a variable by reference. This is made possible by prefixing the function name with the '&' by reference operator and makes it possible for us to return multiple variables from a function.

tags

Comments:

Featured Script

WDP Zoomer - jQuery image zoomer
A javascript/jQuery image zoomer... (read more)