Jump to content

PHP and passing by reference


CroNiX

Recommended Posts

I am really confused on this topic.  I took C++ about 18 years ago (never used it) and it was all about passing by reference.  On php.net (http://uk.php.net/references) they state that "References in PHP are a means to access the same variable content by different names. They are not like C pointers; instead, they are symbol table aliases."

 

Ive been programming in php for about 3 years now and have never come across a case where I needed to pass by reference.  Maybe I should have, but I really am having a hard time understanding when you NEED or SHOULD pass by reference.  Can someone give me some concrete examples when it should be used?  What is the advantage, etc.?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/125313-php-and-passing-by-reference/
Share on other sites

You likely have indeed passed by reference without realizing it... have you ever used preg_match_all()? shuffle()? passed classes? many function in php use references. They're invaluable in that they remove repeated copying of large variable content such as objects, arrays, etc when they do not need to be copied, saving valuable execution time.

When you need to modify a variable outside the scope of a function lets say a counter as an example:

 

$counter = 1;

function startCounting(&$counter, $stopAt) {
for($x = 0; $x < $stopAt; $x++) {
 $counter++;
}
}
startCounting($counter, 10);
// displays 11
print $counter;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.