Jump to content

Call by Value/Referance


Lara_Shadow

Recommended Posts

Here's the code snippet that I was talking about. I just learned about this in my C++ class, actually, and was surprised to see that PHP does this as well. I haven't run into this before in a PHP based application.

 

Basically, the difference is that "Pass by Value" passes the value of the variable, while "Pass by Reference" passes the reference to the variable -- the variable itself. This will allow the function to modify variable passed to it. In this example, I start by setting a variable, $var, to 1. When I pass that variable to the by_value() function, you'll notice that the value of $var doesn't change. But, when I pass it to by_reference(), $var itself changes from 1 to 2.

 

(I'm only just getting into this concept, so if there is a better explanation or I've said something that isn't completely true, feel free to comment)

 

$var = 1;



// This is an example of "Pass by Value"
function by_value($i)
{
   $i++;
}

// When we pass $var into the function, it just passes $var's value, 1, not var itself.
// Any changes made within the function won't affect $var, so $var's value doesn't change.
// This will echo "1".
by_value($var);
echo "Pass by Value: " . $var . "
";



// This is an example of "Pass by Reference" (notice the "&" before the variable name)
function by_reference(&$i)
{
   $i++;
}

// When you pass $var into the function, it isn't passing the value, but $var itself
// You can think of it like this: rather than $i just holding the value of $var, $i becomes $var,
// so any changes made to $i also affect $var.
// this will echo "2"
by_reference($var);
echo "pass by Reference: " . $var;

?>

 

More info:

http://php.net/manual/en/language.references.pass.php

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  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.

Loading...
×
×
  • Create New...