Passing by reference in PHP

I was just reading up on some PHP while I work on one of my final projects and I came across the topic of passing by reference. Which if you are not familiar with it, this is the PHP.net reference page. I had no idea that it existed and it instantly reminded me of the past three weeks of C++ where we have been discussing and using pointers as a means of “returning” more than one value from a function.

A good explanation of a reference is:

“References are a way to have multiple variables referencing the same variable container using different names — so whatever name you’re using an operation on that variable will always have an effect on the others.” – Johannes Schl├╝ter

My experience with pointers and passing by reference has been in the classroom and so the only benefit I have seen is that you can modify variables outside of a function. Check this snippet out for instance:

function addOne(&$input){
$input++;
}
$var = 1;

addOne($var);

//returns 2.

Conclusion

I don’t know that I would really pass by reference outside of the classroom at this stage as I have not encountered a situation where I needed to return or modify more than one value at a time.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>