Functions and Passing by Reference

A function can be written to accept parameters (variable) or not. A parameter name is local to a function unless you tell it otherwise by using the global statement. Thus, you can pass a parameter called $string and name the accepted parameter $string also and they won’t interfere with each other. For example

In the function above, $string outside of the function will remain “car” while $string inside the function will become “cars”.

Typically, when you write a function like the one above that takes a passed parameter, you want to modify the passing variable. This is most often done by returning the result of your function. So, the above example would become:

Now, the $string variable outside the function will start as “car” and after calling the function will become “cars.”

As hinted at above, you can accomplish the same thing without passing a parameter if you use the global statement. For example:

As mentioned, when you pass a variable parameter the passed and received variables remain distinct variables in the eyes of PHP, regardless of their name. But, you can also accomplish the same function work by using something called a reference. Marking a variable as “passed by reference” is done in the function definition by preceding the parameter name with an ampersand (&). Let’s compare the following function two functions:

The first piece of code, which we saw earlier, passes a copy of $string into the function, modifies the copy of $string that is unique to the function and finally uses the return command to pass the result back to the main script where it is then copied back into the original $string variable.

The second example, by contrast, passes $string in by reference, and it is modified directly inside the function. Thus we can just call the function directly. If you think about it, this method is actually more similar to using the global command.

One key thing to remember is that a reference is a reference to a variable. If you define a function as accepting a reference to a variable, you cannot pass a constant into it. Thus, for our function called plural(), you cannot call the function using plural ("car") since “car” is not a variable and therefore cannot be treated as a reference.

Like this content? Why not share it?
Share on FacebookTweet about this on TwitterShare on LinkedInBuffer this pagePin on PinterestShare on Redditshare on TumblrShare on StumbleUpon
There Are No Comments
Click to Add the First »