Jump to content

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;

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.