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)
<?php
$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 . "<br/>";
// 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
Benjamin Falk |
Falken Creative :
TwitterSkills: Photoshop, Illustrator, HTML, CSS, jQuery, PHP and CodeIgniter